ReactJS - 在渲染组件之前加载数据

Ade*_*del 3 reactjs

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

我已经使用了API调用componentDidMount,componentWillMount并试图setState()让我的数据处于状态.但他们在我的情况下不起作用.

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

这是我的代码:

  componentDidMount() {
    api.get(id).then((response) => {
     this.setState({response,});
  });
Run Code Online (Sandbox Code Playgroud)

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

如何更改修复加载问题的方法?

Tim*_*mes 7

你这样做的方式,可以在render方法中验证响应状态对象,如果它是null/empty,则返回<div>Loading...</div>.

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

例如

render(){

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

    return (
        <div>Proper Stuff</div>
    );
}
Run Code Online (Sandbox Code Playgroud)

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

constructor(props){
    super(props);

    this.state = {
        response: {...}
    };
}
Run Code Online (Sandbox Code Playgroud)