如果需要如何加载数据?反应/终极版。无SSR
How to load data if needed ? React / Redux. No SSR
是否可以根据需要加载数据?
例如:我第一次加载list of challenges
然后我去了详情页面。现在我将刷新页面并会出现类似 challenges undefined
的错误,因为仅在加载 list of challenges
时调用 api
。
所以问题是如何仅在 store
为空时再次调用 api?
谢谢!
你可以这样设置你的状态:
this.setState({
challenges :data
});
当您导航到详细信息页面时,您可以将其作为道具传递给子组件:
render{
return(
<Details challenges={this.state.challenges }/>
);
}
在详细组件中,您可以访问数据
this.props.challenges
并将其存储在变量或您的组件状态中。
这样您就可以始终保留您的数据
只需将 initialState 的 challenges 属性设置为 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});
})
}
}
感谢您的回答,但上面的解决方案不是我需要的。
所以我通过 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>
);
谢谢!
是否可以根据需要加载数据?
例如:我第一次加载list of challenges
然后我去了详情页面。现在我将刷新页面并会出现类似 challenges undefined
的错误,因为仅在加载 list of challenges
时调用 api
。
所以问题是如何仅在 store
为空时再次调用 api?
谢谢!
你可以这样设置你的状态:
this.setState({
challenges :data
});
当您导航到详细信息页面时,您可以将其作为道具传递给子组件:
render{
return(
<Details challenges={this.state.challenges }/>
);
}
在详细组件中,您可以访问数据
this.props.challenges
并将其存储在变量或您的组件状态中。 这样您就可以始终保留您的数据
只需将 initialState 的 challenges 属性设置为 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});
})
}
}
感谢您的回答,但上面的解决方案不是我需要的。
所以我通过 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>
);
谢谢!