mapStateToProps中未定义Redux状态

esa*_*inu 23 javascript reactjs immutable.js redux react-redux

我目前正在学习教程.我mapStateToProps在下面的代码中遇到了一些障碍:

import React from 'react';
import Voting from './voting';
import {connect} from 'react-redux';

const mapStateToProps = (state) => {
  return {
    pair: state.getIn(['vote','pair']),
    winner: state.get('winner')
  };
}

const VotingContainer = connect(mapStateToProps)(Voting);
export default VotingContainer;
Run Code Online (Sandbox Code Playgroud)

以下是导入的投票组件:

import React from 'react';
import Vote from './Vote';
import Winner from './winner';

const Voting = ({pair,vote,hasVoted,winner}) =>
  <div>
    {winner ? <Winner winner={winner}/>  :
      <Vote pair={pair} vote={vote} hasVoted={hasVoted}/>
    }
  </div>

export default Voting;
Run Code Online (Sandbox Code Playgroud)

它应该从pair道具渲染两个按钮.该vote道具是将上点击执行的功能,hasVoted真正当禁用按钮和获奖者只呈现赢家组件,如图所示.

该状态应该是一个看起来像这样的immutableJS地图:

Map({
  vote:{
    pair:List.of('Movie A','Movie B')
  }
});
Run Code Online (Sandbox Code Playgroud)

相反,我收到一个错误,说状态在state.getIn行中是未定义的.

设置状态的代码在索引中:

const store = createStore(reducer);

const socket = io(document.location.protocol + '//' + document.location.hostname + ':8090');
socket.on('state', state => store.dispatch({
  type: 'SET_STATE',
  state
}));
Run Code Online (Sandbox Code Playgroud)

store.getState()在设置后记录,它是按预期但undefinedmapStateToProps.我还在上面的上下文中记录了状态变量,它也是预期的.

我也正常设置状态,它出奇地工作!:

store.dispatch({
  type: 'SET_STATE',
  state: {
    vote: {
      pair: ['Movie A', 'Movie B']
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

上面的状态值正是从服务器接收的值

最后这是我的减速机的样子:

import React from 'react';
import {Map, fromJS} from 'immutable';

const reducer = (state = Map(), action) => {
  switch (action.type) {
    case 'SET_STATE':
      return state.merge(action.state);
  }
}

export default reducer;
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

编辑:我意识到mapStateToProps之后没有被调用store.dispatch().我查看了文档,原因可能mapStateToProps是没有被调用,而且不是其中之一.

Dea*_*ish 49

您的reducer在switch语句中没有默认操作.这就是为什么即使你在reducer params中提到初始状态,undefined也会作为存储初始状态返回

import React from 'react';
import {Map,fromJS} from 'immutable';

const reducer = (state = Map() ,action) => {
  switch(action.type){
    case 'SET_STATE': return state.merge(action.state);
    default:
      return state;
  }
}

export default reducer;
Run Code Online (Sandbox Code Playgroud)

添加默认语句将解决问题:)