Redux mapStateToProps返回未定义

Joh*_*Doe 0 javascript state reactjs redux react-redux

Redux已成功存储和更新状态。减速器似乎正常工作。我可以使用this.props.dispatch。但是,当涉及到详细说明该信息时(即,this.props.array我似乎总是不确定)。

减速器:

export default function array(state = {}, action) {
    switch (action.type) {
      case "UPDATE_ARRAY":
        state.array = action.array
        return state;
      default:
        return state;
  }
}
Run Code Online (Sandbox Code Playgroud)

状态感知组件:

  constructor(props) {
    super(props);
    this.state = {
      array: array
    }
  }
Run Code Online (Sandbox Code Playgroud)

-

  self.props.dispatch({
    type: 'UPDATE_ARRAY',
    array: array
  })
Run Code Online (Sandbox Code Playgroud)

-

const mapStateToProps = (state) => {
      return {
        messages: state.messages,
        array: state.array
      };
    };

    export default connect(mapStateToProps)(Component);
Run Code Online (Sandbox Code Playgroud)

当我定义一个空数组时,这似乎只能保存状态btw。这似乎不对,我认为Redux的初衷是一个独立的商店?更新变量似乎会破坏目标。

将不胜感激。

Raj*_*pta 5

export default function array(state = {}, action) {
switch (action.type) {
  case "UPDATE_ARRAY":state={
        ...state,
        array:action.array
                   }
    return state;
  default:
    return state;
Run Code Online (Sandbox Code Playgroud)

}}

  • 您应该始终不变地更新状态,而不是改变当前应用程序的状态,而应该创建另一个对象并返回该状态。状态应该是不可变的,更改状态的唯一方法是创建一个新的状态。这有助于提高的性能。应用程序。
  • 我不确定您的应用程序是否具有多个reducer,如果具有,则必须使用Combine reducer方法。因此在mapsStateToProps中访问state.array就像这样

    const mapStateToProps =(state)=> {return {

    messages: state.{reducer_name}.message,
    array: state.{reducer_name}.array
    
    Run Code Online (Sandbox Code Playgroud)

    }; };

  • 代替“ reducer_name”,您必须指定在组合减速器中定义的reducers_name

  • 最后一个mapStateToProps返回数组,在props中不处于组件状态。您可以通过{this.props.array}这样的方式进行访问,您无法在componentDidMount和componentWillRecieveProps中设置组件状态(如果aysnc操作)。