保持容器之间的一致状态

时间:2016-05-24 11:23:08

标签: reactjs redux

我正在使用React / Redux应用。在我的应用程序中,我有一个AllRestaurants'容器遍历JSON对象数组并创建餐馆列表。

然后我使用React-Router进行链接,以允许点击该列表中的餐馆名称并呈现“餐厅”。将展示特定餐厅及其所有细节的容器。

点击一家餐馆的名字,然后点击“AllRestaurants'列表容器将替换在'餐厅的页面上。容器,我有餐馆'和' selectedRestaurant'我的州有;然而,当我在'餐厅'的页面上?容器已经加载并点击刷新,我的状态中的selectedRestaurant为空(因为它是默认状态)。

我如何设置此设置,以便我的州已经知道我选择的餐厅,并且如果'餐厅'容器已经加载了?

谢谢!

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(reducer)

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(reducer)

const SELECT_RESTAURANT = 'SELECT_RESTAURANT';

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

1 个答案:

答案 0 :(得分:0)

另一个解决方案是检查餐馆的状态及其null然后调用将从服务器获取数据并恢复状态的操作。

例如:

  componentWillMount() {
    if(this.props.restaurant.length==0){
      this.props.youractions.call_the_actions()
    }
  }