【问题标题】:ReactJS - load the data before rendering the componentReactJS - 在渲染组件之前加载数据
【发布时间】:2017-10-20 14:47:49
【问题描述】:

在 ReactJS 中,我将路由更改为带有“id”的新路由,然后基于此“id”,我必须调用 API 并获取数据。

我在componentDidMount 和componentWillMount 中使用了API 调用,并尝试setState() 让我的数据处于状态。但它们在我的情况下不起作用。

问题出在render() 部分,当我想使用我的数据(来自状态)时,数据不存在,因为 API 调用需要一些时间来更新状态。

这是我的代码:

  componentDidMount() {
    api.get(id).then((response) => {
     this.setState({response,});
  });

用这种方法,我想要的时候没有数据(渲染方法),它最终会处于状态但为时已晚!

如何改变我的方法来解决加载问题?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    按照您的操作方式,您可以在您的渲染方法中验证响应状态对象,如果它为空/空,则返回<div>Loading...</div>。

    当您的状态根据响应更新时,组件将自动重新渲染。这一次,对象将被填充,您可以返回您的组件 HTML。

    例如

    render(){
    
        if (!this.state.response){
            return <div>Loading...</div>
        }
    
        return (
            <div>Proper Stuff</div>
        );
    }
    

    编辑 在站点注释中,如果您在构造函数中设置初始状态,则可以确保对象不为空,而只是具有空值/空值。这也可能有助于取决于您的 render 方法正在做什么,例如

    constructor(props){
        super(props);
    
        this.state = {
            response: {...}
        };
    }
    

    【讨论】:

      【解决方案2】:

      你的渲染代码应该是

      render(){
       return({this.state.response?
                <div> Render your component here</div>: 
                <div> Loading ... </div>});
      }
      

      这样,您的组件在获得数据之前不会渲染,而是显示 Loading ... 文本。

      【讨论】:

        猜你喜欢
        • 2016-06-09
        • 2021-04-19
        • 2018-11-29
        • 2019-08-09
        • 1970-01-01
        • 1970-01-01
        • 2017-01-06
        • 1970-01-01
        相关资源
        最近更新 更多