简体   繁体   English

如何在 ReactJS function 中获取最新的 state 值?

[英]How to get latest state value in ReactJS function?

Below function is called from 2-3 places depending on the situation. function下面根据情况从2-3个地方调用。 I am making api call according to the value in my state like this:我正在根据我的 state 中的值进行 api 调用,如下所示:

myFunction = () => {
    # do something
    const { myVariable } = this.state;
    if (!myVariable.item) {    // myVariable.item is not getting latest variable
        makeAPICall().then(data => {
            myVariable.item = data;
            this.setState({ myVariable });    // setting in state here
        });
    }
}

After one call to the above function, the state myVariable should be set with item, but when it is called again just after that, myVariable.item is undefined.一次调用上述 function 后,state myVariable应该设置为 item,但是当它再次调用时, myVariable.item未定义。

What can I do to get the latest value from my state to prevent another api call?我该怎么做才能从我的 state 中获取最新值,以防止另一个 api 调用?

Problem: State Mutation问题:State 突变

Your variable myVariable is an object reference to the object in this.state.myVariable .您的变量myVariable是 object 对 this.state.myVariable 中的this.state.myVariable的引用。 You cannot assign to it like myVariable.item = data because this is an illegal mutation of state.您不能像myVariable.item = data那样分配给它,因为这是 state 的非法突变。

Solution解决方案

You need to create a new object, which you can do with object spread syntax.您需要创建一个新的 object,您可以使用 object 扩展语法来完成。

myFunction = () => {
    const { myVariable } = this.state;
    if (!myVariable.item) {
        makeAPICall().then(data => {
            this.setState({ 
               myVariable: {
                  ...myVariable, // copy all properties
                  item: data, // override item property
               }
            });
        });
    }
}

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

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