我正在使用 react-router 并导航到在 URL 中获取 ID 的组件,并且必须使用此 ID 在操作的帮助下从服务器获取数据。
目前我正在 componentWillMount
Hook 中调用 Action 创建者。
到目前为止,这有效,但带来了一个问题。
在渲染方法中,我必须检查 myData
是否真的存在及其所有属性,然后才能真正渲染。
@connect(state => {myData: state.etc.myData})
export default class extends React.Component {
componentWillMount = () => {
this.props.dispatch(
ActionCreators.getData(this.props.params.id)
)
}
render() {
if (this.props.myData.hasNotLoaded) return <br/>
...
}
}
是否有另一种方法可以在渲染前将数据放入存储中而无需手动检查?
最佳答案
您可以订阅路由器的 onEnter
钩子(Hook)并从哪里分派(dispatch)操作。
const store = configureStore()
const routing = (<Router>
<IndexRoute onEnter={()=>store.dispatch(myLoadDataActionCreator())}/>
</Router>)
这样你就可以避免上一个答案中的 setState
并且不要将组件与 redux 绑定(bind)。
关于react-router - 加载服务器数据的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31789639/