简体   繁体   English

无法在回调函数中更新组件的状态

[英]Can't update a component's state inside a callback function

constructor(props) {
    this.state = {contents: []};
}

componentDidMount() {
    var self = this;
    console.log('> Manage mounted');
    ServerService.getServers(
        Parse, 
        self.props.parentState.state.activeAccount,
        (error, results) => {
            if (error) {
                throw new Error(error); 
            }

            this.setState((prevState, props) => ({
              contents: results 
            }));
        }
    );
}

Hi there, I have this code above. 嗨,我上面有这段代码。 I have a component named Manage and Servers. 我有一个名为“管理和服务器”的组件。 Now, from the time the Manage component is mounted, I wanted to populate it's this.state.contents by means of ServerService.getServers() . 现在,从安装Manage组件开始,我想通过ServerService.getServers()填充它为this.state.contents。 The utility returns a results , which is an array from a callback function. 该实用程序返回results ,该results是回调函数的数组。 Though, the state is not getting in. Is this the correct way of updating a component's state from the within a callback function? 但是,状态并没有进入。这是从回调函数中更新组件状态的正确方法吗?

Furthermore, I am passing the said state to a child component named MainContent eg <MainContent contents={this.state.contents} /> , and watching it as a props, when the component is mounted 此外,我将上述状态传递给名为MainContent的子组件,例如<MainContent contents={this.state.contents} /> ,并在安装组件时将其作为道具观看

componentDidMount() {
    console.log('> MainContent is mounted');
    console.log(this.props.contents);
}

The thing is, this.props.contents from MainContent component remains a blank array. 事实是, MainContent组件中的this.props.contents仍然是一个空白数组。 The reason why I am doing this is because I have further usage of the value in contents , as another sets of props for MainContent child components. 为什么我这样做的原因是因为我有在价值的进一步使用contents ,作为另一组的props进行MainContent子组件。

The approach that you are using to update the state is useful in a scenario when you are trying to update a state sort of like 在尝试更新状态之类的情况下,用于更新状态的方法很有用

    this.setState((prevState, props) => ({
          contents: [...prevState.content, props.content]
        }));

ie making use of the previous state as well as props because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state. 即使用先前的stateprops因为this.props和this.state可能会异步更新,因此您不应依赖于它们的值来计算下一个状态。

However you are using setState inside a function and hence this keyword here won't refer to the correct content, you should make use of self also since you are updating the state with a value that is not dependent on state or props and hence you can use the direct approach of updating a state like 然而,你使用的是函数内部的setState,因此this位置的关键字不会指向正确的内容,你应该利用self也因为您正在使用不依赖于国家或道具的值更新状态,因此你可以使用更新状态的直接方法

self.setState({contents: results});

Code: 码:

componentDidMount() {
    var self = this;
    console.log('> Manage mounted');
    ServerService.getServers(
        Parse, 
        self.props.parentState.state.activeAccount,
        (error, results) => {
            if (error) {
                throw new Error(error); 
            }

            self.setState({
              contents: results 
            });
        }
    );
}

As far as getting a blank array in componentDidMount of MainContent is concerned, you will get a bland array because componentDidMount is rendered only on the initial render and since at initial render your this.state.contents is a blank array, you get a empty value. 就在MainContent componentDidMount中获取空白数组而言,您将获得一个平淡的数组,因为componentDidMount仅在初始渲染时渲染,并且由于在初始渲染时this.state.contents是一个空白数组,因此您会得到一个空值。

change that to componentWillReceiveProps 将其更改为componentWillReceiveProps

componentWillReceiveProps(nextProps) {
    console.log("Main content");
    console.log(nextProps.contents);

}

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

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