首页 > 解决方案 > 为什么需要传入 this.state.example 来重新渲染页面?

问题描述

我的渲染中有这个:

{this.availProps(this.state.data)}

this.state.data在 componentOnMount 时使用 fetch 更新

availProps = data =>{
    if (data.length == 0) 
        return (
            <option>"hello"</option>
        )
    else 
    return (    
        <option> "hi" </option>
        )
}

数据提取完成后,它会很好地打印出“hi”。但是,如果我使用:

{this.availProps()}

   availProps = () =>{
        if (this.state.data.length == 0) 
            return (
                <option>"hello"</option>
            )
        else 
        return (    
            <option> "hi" </option>
            )
    }

不起作用。它会打印出“你好”。

这是因为只有在“渲染”中的变量更改/更新时才会重新渲染页面?(在这种情况下,this.state.data)

谢谢

编辑:这是componentDidMount

componentDidMount() {
    this.getDataFromDb()
}


getDataFromDb = () => {
    fetch("http://localhost:3001/api/property")
      .then(property => property.json())
      .then(res => this.setState({ data: res.data }))
      .then(() =>{
          for(var i = 0; i < this.state.data.length; i++) {
              if (this.state.data[i].status == 0)
                  this.state.useData.push(this.state.data[i])
          }
      }).then
    ( ()=> console.log(this.state.useData))
};

标签: javascriptreactjs

解决方案


直接设置属性this.state不会调用渲染方法。

您将不得不使用this.setState({ useData: useData }),以便对运行渲染方法的某些内容发生变化做出反应。

并且由于正在设置的状态基于先前的状态,因此最好使用状态更新器模式及其回调,以便在尝试访问更新状态时可用。

不要直接更新状态

getDataFromDb = () => {
  fetch("http://localhost:3001/api/property")
    .then(property => property.json())
    .then(res => this.setState({
      data: res.data
    }))
    .then(() => {
      // Your computations are based on previous state
      // use the updater function to have access to the latest
      // state as state updates are asynchronous
      this.setState((previousState) => {
        const {
          data
        } = previousState;

        // accessing this.state here might have stale data

        const updatedUseData = data.reduce((acc, obj) => {
          if (obj.status === 0) {
            acc.push(obj);
          }

          return acc;
        }, []);

        // this will invoke the render again as 
        // a state is updated
        return {
          useData: updatedUseData
        }
      }, () => {
        // Use the call back which gets invoked once the state
        // is updated
        console.log(this.state.useData)
      })
    })
}


推荐阅读