2017-07-03 67 views
1

是否可以在需要時加載數據?如何根據需要加載數據? React/Redux。否SSR

例如:第一次我加載list of challenges然後我去了詳細頁面。現在我將刷新頁面,並將出現類似challenges undefined的錯誤,因爲只有在加載list of challenges時才調用api

所以問題是如何僅在store爲空時再次調用api?

謝謝!

+1

你的高階組件應該得到挑戰列表,所以即使它刷新了它也會獲取所有需要的數據。爲避免重新獲取數據,請在點擊API之前檢查該值是否存在於存儲區中。 – Fawaz

回答

0

感謝答案,但解決方案的上面沒有我需要什麼。

所以我實現了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> 
); 

謝謝!

1

你可以設置你的狀態是這樣的:

this.setState({ 
    challenges :data 
}); 

當您導航到詳細信息頁面,那麼你可以通過這個道具兒童組件:

render{ 
    return(
    <Details challenges={this.state.challenges }/> 
); 
} 

詳細組件,您可以訪問數據爲

this.props.challenges 

並將其存儲在變量或組件狀態中。 這樣你可以隨時保留你的數據

1

只需將你的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}); 
     }) 
    } 
} 
相關問題