mapStateToProps

时间:2018-05-28 16:18:25

标签: reactjs redux action state reducers

我一直在尝试从我的vitaminReducer()reducer函数中检索新状态,并通过mapStateToProps连接它。但是当我在console.log状态时,我回来了“状态是{维生素:未定义}”。

这是我正在调用mapStateToProps()的Vitamins组件 (Vitamins.js)

  componentDidMount() {
     this.props.fetchVitamins();
   }

  function mapStateToProps(state) {
     return {
      vitamin: state,
     }
  };

  console.log('the state is', mapStateToProps());

  export default connect(mapStateToProps, { fetchVitamins })(Vitamins);

(reducers.js)

 function vitaminReducer(state = [], action) {
   switch(action.type) {
    case FETCH_VITAMINS_SUCCESS:
      return [
        ...state,
        action.payload.vitamins
      ];
     default:
       return state;
    }
  }


  const reducers = combineReducers({
    vitamin: vitaminReducer,
  });

我通过Express服务器传输数据。我在这里控制了记录的“维生素”并且我得到了数据,所以我知道这不是问题。

(actions.js)

 export function fetchVitamins() {
   return dispatch => {
     return fetch("/users")
       .then(handleErrors)
       .then(res => res.json())
       .then(micros => {
          dispatch(fetchVitaminsSuccess(micros));
          const vitamins = micros.vitamins;
        }
     )};
  };

  export const FETCH_VITAMINS_SUCCESS = 'FETCH_VITAMINS_SUCCESS';

  export const fetchVitaminsSuccess = vitamins => ({
    type: FETCH_VITAMINS_SUCCESS,
    payload: vitamins
  });

如果我这样做:“返回{维生素:状态维生素,}”而不是“返回{维生素:状态,}”,我得到“TypeError:无法读取未定义的属性'维生素'”。但这就是我在reducers.js底部的combineReducers()函数中所谓的vitaminReducer,所以我认为这是正确的方法。

1 个答案:

答案 0 :(得分:0)

感谢大家的投入!我能够让它发挥作用。

我抛弃了mapStateToProps(),而是做了这个

(Vitamins.js)

  componentDidMount() {
    this.props.fetchVitamins();
  }

  renderData() {
   const { vitamins } = this.props.vitamins;
    return vitamins.map((micro, index) => {
      return (
        <option value={micro.value} key={index}>{micro.name}</option>
      )
    })
  }

  export default connect(
   state => ({
     vitamins: state.vitamins
   }),
   {
    fetchVitamins
   },
   )(Vitamins);

我在fetchVitamins()函数

中设置了调度操作

(actions.js)

  export function fetchVitamins() {
   return dispatch => {
      return fetch("/users")
       .then(handleErrors)
       .then(res => res.json())
       .then(micros => {
         dispatch({
           type: "RECEIVE_VITAMINS",
           payload: micros.vitamins
         });
        }
     )};
   };

   export const RECEIVE_VITAMINS = 'RECEIVE_VITAMINS';

在reducer中我将initialState设置为维生素数组,并从我的RECEIVE_VITAMINS操作中传递了micros.vitamins的新状态

(reducers.js)

  const initialState = {
    vitamins: [],
  }

 function vitaminReducer(state = initialState, action) {
   switch(action.type) {
     case RECEIVE_VITAMINS:
      return {
        ...state,
        vitamins: action.payload
      };
  default:
     return state;
  }
}


const reducers = combineReducers({
   vitamins: vitaminReducer,
});

感谢大家的帮助!如果您有任何其他建议,请告诉我:D