简体   繁体   English

如何使用渲染功能上方的更新状态值?

[英]How to use updated state value above render function?

I think it might be silly question to ask but trust me I am stuck to find an answer . 我认为问这个问题可能很愚蠢,但请相信我,我一直在寻找答案。 Actually , I am trying to access updated state value in class function above render function but I am not getting updated value . 实际上,我正在尝试在render函数之上的类函数中访问更新后的状态值,但是我没有得到更新后的值。 when I console value in render function I got updated value . 当我在render函数中控制台值时,我得到了更新的值。 Could someone please help me how to access updated value . 有人可以帮我如何获取更新的价值。

Thanks 谢谢

Code

fetchAgents = e => {
  this.setState({
    value: e.target.value
  });
};

fetchFilteredInventories = e => {
  axios
    .get(`/api/reports/agents/?branch=${this.state.value}`)
    .then(response => {
      this.setState({
        agents: response.data
      });
    });
};

when I try to access updated state value in fetchFilteredInventories I am getting null value . 当我尝试访问fetchFilteredInventories更新状态值时,我得到的是null值。 Could someone help me to achieve my goal 有人可以帮助我实现我的目标吗

setState is asynchronous. setState是异步的。 When you console.log after setState, the state is not changed yet, it is in the process of changing. 在setState之后使用console.log时,状态尚未更改,它正在更改过程中。 Try this 尝试这个

this.setState({
 value : e.target.value
 },()=>console.log(value));

You will see the value is updated. 您将看到该值已更新。 setState allows a callback function as arguement. setState允许使用回调函数作为争论。 So use the callback function to use the updated state value. 因此,请使用回调函数来使用更新的状态值。

Read the docs for further info: https://reactjs.org/docs/state-and-lifecycle.html#using-state-correctly 阅读文档以获取更多信息: https : //reactjs.org/docs/state-and-lifecycle.html#using-state-正确

It depends on where you are calling your fetchFilteredInventories function. 这取决于您在哪里调用fetchFilteredInventories函数。
After a state update in a React component certain lifecycle hooks get called, such as componentWillUpdate , componentDidUpdate . 在React组件中进行状态更新后,将调用某些生命周期挂钩,例如componentWillUpdatecomponentDidUpdate you can read about them in React docs here State and Lifecycle . 您可以在State和Lifecycle的 React文档中阅读有关它们的信息。
Make sure you are calling your API call function at the right moment. 确保在正确的时间调用API调用函数。
If you can, put your whole component code here for better answers. 如果可以,请将整个组件代码放在此处以获得更好的答案。

Try This 试试This

axios.get(`/api/reports/agents/?branch=${this.state.value}`).then(function(response) {
       this.setState({
            agents: response.data
          });
    }.bind(this));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM