简体   繁体   English

在数组上设置状态不起作用本地?

[英]Set State on array not working in react native?

I'm really sorry I'm posting this as it sounds crazy. 我真的很抱歉我发布这个,因为它听起来很疯狂。 I got a method to validate some inputs I have in a form inside a modal. 我有一个方法来验证我在模态中的表单中的一些输入。

So I check on every this.state.variable and doing a push to an aux array to be then set to the original fieldErrors array. 所以我检查每个this.state.variable并按下一个辅助数组,然后设置为原始的fieldErrors数组。

But for some reason, when I check aux before setting, length is 5. After setting to fieldErrors, i notice length is 0. What's going on? 但由于某种原因,当我在设置之前检查aux时,长度为5.设置为fieldErrors后,我注意到长度为0.发生了什么?

Here's the code: 这是代码:

_validateMissingFields: function() {
    var aux = [];

    if (this.state.variable1.length === 0) {
        aux.push('variable1');
    }

    if (this.state.variable2.length === 0) {
        aux.push('variable2');
    }

    if (this.state.variable3.length === 0) {
        aux.push('variable3');
    }

    if (this.state.variable4.length === 0) {
        aux.push('variable4');
    }

    if (this.state.variable5.length === 0) {
        aux.push('variable5');
    }

    console.log(aux.length) // -> shows 5
    this.setState({ fieldErrors: aux });
}

Later on, when I do this.state.fieldErrors.length after this method, shows 0. 稍后,当我在此方法之后执行this.state.fieldErrors.length时,显示0。

By the way, this is how I'm initializing fieldErrors : 顺便说一句,这就是我初始化fieldErrors

getInitialState: function() {
    return {
        variable1: '',
        variable2: '',
        variable3: '',
        variable4: '',
        variable5: '',
        fieldErrors: []
    }
},

React setState is asynchronous which is why this.state cannot be read immediately. React setState是异步的,这就是为什么this.state不能立即读取的原因。

See the docs for more info https://facebook.github.io/react/docs/react-component.html#setstate 有关详细信息,请参阅文档https://facebook.github.io/react/docs/react-component.html#setstate

setState is asynchronous, as has been mentioned a couple times, but it also accepts a callback function as a second parameter so if what you're trying to do with length can be done in a callback you can do something like setState是异步的,正如已经提到的那样,但是它也接受一个回调函数作为第二个参数,所以如果你想要做的长度可以在回调中完成,你可以做类似的事情

this.setState({ fieldErrors: aux }, () => {
  console.log(this.state.fieldErrors.length); // Or whatever you're trying to do
};

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

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