首页 > 解决方案 > 反应数组状态在渲染之前被清除

问题描述

有响应问题。

当进行 ajax 调用以从后端检索数据时,我检索数据,但似乎它在将数据包装在.then(). 在 a .then()then 之外,数据将被清除。

consume 是一个处理 axios 调用的个人模块。

这是问题

componentWillMount() {
    const retrieveLogs = {
      method: "GET",
      url: this.state.url, 
    }
    consume.fetch(retrieveLogs)
      .then(res => {
        if(typeof res.logger === "object"){
          this.setState({
            logs: res.logger,

         })
         console.log(this.state.logs) // show the console log here but
        }
    })
    console.log(this.state.logs) // but shows empty array here why is this ?
  }

标签: javascriptreactjs

解决方案


componentWillMount不安全且已弃用,您不应使用它,请参阅此处的详细信息。最好的方法是用来componentDidMount获取你的数据,然后更新状态。具有空状态的初始渲染是模式,您不必担心。此外,您不应该像那样记录您的状态,记住,setState它是异步的,并且您不能保证在调用时会更新状态console.log,在这种情况下,使用它的第二个参数setState为您提供一个回调,只有在所有更新完成时才会触发.

componentDidMount() {
const retrieveLogs = {
  method: "GET",
  url: this.state.url, 
}
consume.fetch(retrieveLogs)
  .then(res => {
    if(typeof res.logger === "object"){
      this.setState({
        logs: res.logger,

     }, console.log(this.state.logs))

    }
})}

如果您需要在数据到达后执行一些操作,componentDidUpdate请在 props 或 state 发生变化时使用来实现您的自定义逻辑。

componentDidUpdate(prevProps, prevState){
   if(prevProps.item !== this.props.item)
       this.setState({item}, console.log(this.state.item))
}

推荐阅读