在渲染反应之前设置状态

时间:2018-05-09 10:35:24

标签: reactjs

我有App.js,里面有一个组件。将其命名为Example。我想用Example设置App.state的道具。例如,Example包含道具:nameid。在App我想要从服务器获取我想要的数据,并将其设置为App的状态,然后将它们分配给Example' s道具,在应用程序渲染之前。这里的问题是我读到componentWillMount(),但React文档说这不是最好的方法。那么,最好的方法是什么?

2 个答案:

答案 0 :(得分:2)

一般方法是在response内存储ajax App,当响应保存到状态时,使用从响应中获取的数据呈现Example组件

class App extends React.Component
  state = { response: null }

  componentDidMount() {
    runYouFetchHere
      .then((response) => this.setState({ response }))
  }

  render() {
    const { response } = this.state

    if (response === null) { return null }

    return (
      <Example name={response.name} id={response.id} />
    )
  }
}

答案 1 :(得分:0)

当react组件中有更新时,将调用以下任何更新方法。

https://reactjs.org/docs/react-component.html#updating

尝试在

中设置状态
componentWillRecieveProps(){
    this.setState({ })
}
相关问题