从父组件接收道具时获取异步数据的setState

时间:2018-01-23 08:35:43

标签: javascript reactjs ecmascript-6

我有componentA作为容器,调用api,我想将数据传递给作为组件的表单

<form data={res.body.data} />

所以在我可以setState的形式?因为form拥有自己的状态。不能在表单组件的构造函数中执行它,因为它是异步数据。

4 个答案:

答案 0 :(得分:1)

根据您的有限代码,我想您需要结帐componentWillReceiveProps(object nextProps)。您可以检查从数据传递的异步数据作为组件Form的支柱,如if (!!nextProps.data) { ... // data is ready}

答案 1 :(得分:0)

您可以等待呈现表单组件,直到API组件获取数据。这样您就可以确保始终拥有数据。

<强> API

fetch() {
  (...) // Do the fetch and setState
  this.setState({ data: res.body.data });
}

render() {
  return (
    <div>
      {this.state.data ? <form data={this.state.data} /> : null}
    </div>
  );
}

答案 2 :(得分:0)

这很容易。您需要使用componentWillReceiveProps

  

在安装的组件之前调用componentWillReceiveProps()   收到新的道具。如果您需要更新状态以响应   prop更改(例如,重置它),您可以比较this.props   和nextProps并使用this.setState()执行状态转换   这种方法。

class Form extends Component {
  componentWillReceiveProps(nextProps) {
    /* make your verifications or whatever */
    this.setState(/* your new state */);
  }

  render() { /* ... */ }
}

答案 3 :(得分:-2)

以Redux形式:

您可以通过在状态中设置initialValues来加载数据。

收到数据后,您可以将数据存储在reducer中,然后将initalValues与该reducer连接。

请参阅此链接以供参考: https://redux-form.com/7.2.1/examples/initializefromstate/