我有一些路线,我想在每个路线发生变化时在客户端获取数据。
我在 componentDidMount
中调用 fetch 函数,如下所示:
componentDidMount() { this.props.fetchSubmitInitialData(); }
但是在 render()
函数中我无法访问新的 Redux 属性。
最佳答案
how I recognize the data has been received in render function
从某种意义上说,您不知道已收到数据,您的渲染函数只是渲染任何状态的 View 。只是当接收到数据时,状态(或从 redux 状态存储传递的 props)发生了变化。因此,下次调用 render()
时,它会针对更新后的值运行,并为您提供当前状态的更新 View 。
这是一个按时间顺序排列的示例:
假设你的初始状态是这样的
state:
loading: true
loaded: false
data: null
因此,在组件呈现的这个阶段,state.loading
为 true
,因此您可能会显示一条 Loading... 消息,例如
安装组件后,您会获取数据,因此会发生调用并返回数据,并且状态会更新为例如
state:
loading: false
loaded: true
data: {'hello': 'world'}
现在,您的渲染函数发现 state.loaded
为 true
,因此它可以继续渲染 state.data
中数据的 View >
关于javascript - 当路线改变时 react 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44862271/