2016-05-24 25 views
2

我正在使用React/Redux應用程序。在我的應用程序中,我有一個「AllRestaurants」容器遍歷一組JSON對象並創建一個餐館列表。保持容器之間的一致狀態

然後,我使用React-Router進行鏈接,以允許點擊該列表中的餐廳名稱並呈現將包含該特定餐廳及其所有細節的「餐館」容器。

點擊餐廳名稱並在'餐館'容器的頁面上替換'AllRestaurants'列表容器後,我的狀態中確實有'餐廳'和'selectedRestaurant';然而,當我在'Restaurant'容器已經加載的頁面上點擊刷新時,我的狀態下的selectedRestaurant爲null(因爲這是默認狀態)。

如何設置此設置,以便我的狀態已經知道我選擇的餐廳,並且已設置「餐館」容器是否已裝入?

謝謝!

AllRestaurants.js(容器)

import React, { Component } from 'react'; 
import { connect } from 'react-redux'; 
import { Link } from 'react-router'; 
import { bindActionCreators } from 'redux'; 
import { selectRestaurant } from '../../actions/restaurantActions'; 

class AllRestaurants extends Component { 
    renderRestaurants() { 
    const allRestaurants = this.props.restaurants.map((restaurant) => { 
     return (
     <li 
      key={restaurant.name} 
      onClick={() => this.props.selectRestaurant(restaurant)} 
     > 
      <Link to={`/restaurants/${restaurant.linkName}`}> 
      <h1>{restaurant.name}</h1> 
      </Link> 
     </li> 
    ); 
    }); 
    return allRestaurants; 
    } 

    render() { 
    return (
     <div> 
     <ul>{this.renderRestaurants()}</ul> 
     </div> 
    ) 
    } 
} 

function mapStateToProps(state) { 
    return { 
    restaurants: state.restaurants, 
    } 
} 

function mapDispatchToProps(dispatch) { 
    return bindActionCreators({ 
    selectRestaurant: selectRestaurant, 
    }, dispatch); 
} 

export default connect(mapStateToProps, mapDispatchToProps)(AllRestaurants); 

index.js(減速器)

import { combineReducers } from 'redux'; 
import allRestaurantsReducer from './allRestaurantsReducer'; 
import selectedRestaurantReducer from './selectedRestaurantReducer'; 

const rootReducer = combineReducers({ 
    restaurants: allRestaurantsReducer, 
    selectedRestaurant: selectedRestaurantReducer, 
}); 

export default rootReducer; 

restaurantActions.js(動作)

const SELECT_RESTAURANT = 'SELECT_RESTAURANT'; 

export function selectRestaurant(restaurant) { 
    return { 
    type: SELECT_RESTAURANT, 
    payload: restaurant, 
    } 
} 

SelectRestaurantReducer.js(減速)

const SELECT_RESTAURANT = 'SELECT_RESTAURANT'; 

export default function(state = null, action) { 
    switch(action.type) { 
    case SELECT_RESTAURANT: 
     return action.payload; 
    default: 
     return state; 
    } 
} 
+0

通過 「刷新頁面」 你的意思是刷新瀏覽器,是否正確? – Banjer

+0

是的,瀏覽器刷新。 – hidace

+0

我很好奇這裏的最佳做法,但我相信你需要從服務器端爲每個[Redux Store文檔]提供初始狀態(http://redux.js.org/docs/basics/Store的.html)。因此,如果您在瀏覽器上進行刷新,它會從服務器請求示例'/ restaurants/some-restaurant',並且服務器從DB加載該json並將其放入存儲中,格式與客戶端讓你從'/ restaurants'導航。如果React/Redux可以自動處理從父容器/組件(餐館列表)加載狀態,那將會很好。 – Banjer

回答

0

另一種解決方案是,檢查餐館的狀態,那麼它的零調用會從服務器上獲取數據,並恢復狀態的行動。

例如:

componentWillMount() { 
    if(this.props.restaurant.length==0){ 
     this.props.youractions.call_the_actions() 
    } 
    } 
相關問題