【问题标题】:React accessing state before ComponentDidMount在 ComponentDidMount 之前响应访问状态
【发布时间】:2018-09-17 00:27:44
【问题描述】:

当我尝试访问在ComponentDidMount 中设置的状态变量时,react 会引发未定义的错误。这是因为我相信当我在ComponentDidMount 中调用提取apisetState 时,该值还没有准备好(async 的东西)。是否有适当的方法来延迟渲染直到 setState 调用完成或其他方式在调用渲染之前完全更新状态?

【问题讨论】:

标签: reactjs


【解决方案1】:

我认为下面的代码将让您基本了解获取数据和渲染的工作原理。

class App extends Component {
    state = { 
        data:{},
        loading:true,
        error:null,
     }
     componentDidMount = () => {
        fetch('https://example.com/api/article')
        .then((response) => {
          return response.json();
        })
        .then((json) => {
          this.setState({
            data:json,
            loading:false,    
          }) 
          .catch(error => {
            this.setState({
                error,
                loading:false,
              })  
          });
        });

     }

    render() {
        const {data,error,loading} = this.state;
        if(loading){
            return "Loading ..."
        }
        if(error){
            return "Something went wrong."
        }
        return 'your actual render component or data';
    }
}

export default App;

【讨论】:

    猜你喜欢
    • 2020-09-17
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 2019-12-22
    • 2015-07-25
    • 1970-01-01
    相关资源
    最近更新 更多