简体   繁体   English

状态在mapStateToProps中未定义

[英]State is undefined in mapStateToProps

I've been trying to retrieve the new state from my vitaminReducer() reducer function, and connect it through mapStateToProps. 我一直在尝试从我的VitaminReducer()reducer函数中检索新状态,并通过mapStateToProps连接它。 But when I console.log the state, I get back "the state is {vitamin: undefined}". 但是,当我用console.log记录状态时,我会返回“状态为{维生素:未定义}”。

This is the Vitamins component where I'm calling mapStateToProps() (Vitamins.js) 这是我调用mapStateToProps()(Vitamins.js)的Vitamins组件。

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

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

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

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

(reducers.js) (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,
  });

I have the data coming through an Express server. 我有通过Express服务器发送的数据。 I've console logged "vitamins" here and I get the data back, so I know that's not the issue. 我已经在控制台上记录了“维生素”,然后我又获得了数据,所以我知道这不是问题。

(actions.js) (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
  });

If I do: "return { vitamin: state.vitamin, }" instead of "return { vitamin: state, }", I get back "TypeError: Cannot read property 'vitamin' of undefined". 如果我这样做:“返回{维生素:state.vitamin,}”而不是“返回{维生素:state,}”,我将得到“ TypeError:无法读取未定义的属性'维生素'”。 But that's what I called vitaminReducer in my combineReducers() function at the bottom of reducers.js, so I thought that was the right way to do it. 但这就是我在reducers.js底部的CombineReducers()函数中所谓的VitaminReducer的原因,所以我认为这是正确的方法。

Thank you everyone for your input! 谢谢大家的投入! I was able to get it working. 我能够使它工作。

I ditched the mapStateToProps() and instead did this 我抛弃了mapStateToProps(),而是这样做了

(Vitamins.js) (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);

I set the dispatch action inside of the fetchVitamins() function 我在fetchVitamins()函数内部设置了调度动作

(actions.js) (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';

In reducers I set the initialState to the vitamins array, and passed the new state of micros.vitamins from my RECEIVE_VITAMINS action 在减速器中,我将initialState设置为维生素数组,并从RECEIVE_VITAMINS动作中传递了micros.vitamins的新状态。

(reducers.js) (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,
});

Thanks everyone for your help! 谢谢大家的帮助! Let me know if you have any other suggestions :D 让我知道您是否还有其他建议:D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM