为什么this.setState不更新状态对象?

时间:2018-12-06 01:16:27

标签: reactjs graphql state

我正在React组件中运行一个简单的方法。计算完值后,我希望将它们设置为状态对象并重新渲染组件。

以下是相关代码:

`class ManageAuthors extends Component {
  state = {authors: [], allAuthors: []};

  authorLists = allPotentialAuthors => {
    const allAuthors = allPotentialAuthors.map(mem => ({...mem, isCurrent: true});
    const authors = this.props.authors.filter({_some other filter code_});
    this.setState({authors, allAuthors});
};

  render() {
    const {authors, allAuthors} = this.state;
    console.log('state:', authors, allAuthors);
    return (
      <Query query={query}>
        {({loading, data}) => {
          if (!loading && data) {
            this.authorLists(data.authors)
          }
          return (_stuff to return_);
        }}
      </Query>
    );
  };
};`

查询将正确触发并返回数据,并将该数据发送到authorLists方法。每个const变量都会计算正确的值。但是当调用this.setState方法时,实际上没有任何更新。就像this.setState方法没有触发一样。是否有某些东西可以阻止this.setState方法工作/更新本地状态对象?

2 个答案:

答案 0 :(得分:0)

setState并不总是立即更新状态。如果您需要立即访问该变量,则可以传递函数setState并在那里使用该变量。

例如:

this.setState({authors, allAuthors}, () => {
   //do something with authors or allAuthors or both
   console.log(authors); console.log(allAuthors); //log it to see if you get desired result
  }
);

React Documentation解释了这个陷阱:

  

setState()并不总是立即更新组件。它可能   批处理或将更新推迟到以后。这使得阅读this.state   在调用setState()之后立即发生潜在的陷阱。相反,使用   componentDidUpdate或setState回调(setState(updater,   回调)),保证在更新后都会触发   已应用。

可以阅读有关此here的更多信息。或在React的文档站点上搜索“ setState”。

答案 1 :(得分:-1)

更正以下行:

this.setState({authors, allAuthors});

this.setState({authors: allAuthors});
相关问题