是否可以在需要时加载数据?如何根据需要加载数据? React/Redux。否SSR
例如:第一次我加载list of challenges
然后我去了详细页面。现在我将刷新页面,并将出现类似challenges undefined
的错误,因为只有在加载list of challenges
时才调用api
。
所以问题是如何仅在store
为空时再次调用api?
谢谢!
是否可以在需要时加载数据?如何根据需要加载数据? React/Redux。否SSR
例如:第一次我加载list of challenges
然后我去了详细页面。现在我将刷新页面,并将出现类似challenges undefined
的错误,因为只有在加载list of challenges
时才调用api
。
所以问题是如何仅在store
为空时再次调用api?
谢谢!
感谢答案,但解决方案的上面没有我需要什么。
所以我实现了onEnter
挂在Route
。
这里是我的方法:
export default function(store, history) {
const requireChallenges = (nextState) => {
if(!challengesIsLoaded(store.getState())) {
store.dispatch(fetchChallenges());
}
};
return (
<Provider store={store}>
<Router onUpdate={() => window.scrollTo(0, 0)} history={history}>
<Route path="/challenges/" component={ChallengesScene} onEnter={requireChallenges} />
</Router>
</Provider>
);
谢谢!
你可以设置你的状态是这样的:
this.setState({
challenges :data
});
当您导航到详细信息页面,那么你可以通过这个道具儿童组件:
render{
return(
<Details challenges={this.state.challenges }/>
);
}
详细组件,您可以访问数据为
this.props.challenges
并将其存储在变量或组件状态中。 这样你可以随时保留你的数据
只需将你的initialState的挑战属性设置为null,并检查在调用API之前是否定义了state.challenges
。
例如:
constructor(props) {
super(props);
this.state = {challenges: null}
}
componentDidMount() {
if (!this.state.challenges) {
MyAPI.getChallenges().then(function(result) {
this.setState({challenges: result.challenge});
})
}
}
你的高阶组件应该得到挑战列表,所以即使它刷新了它也会获取所有需要的数据。为避免重新获取数据,请在点击API之前检查该值是否存在于存储区中。 – Fawaz