React-Redux正在为每个化简函数创建存储状态。为什么?以及如何解决?

时间:2019-05-06 22:55:40

标签: reactjs react-redux

我目前有两个化简器,出于某种原因,当我控制台日志状态时,我有两个状态副本,每个化简器一个。此外,没有“主要状态”或其他任何内容。这不可能在这里,我想找出解决方法。

我尝试将initialState进出combineReducers以及进出减速机。无论我做什么,在我目前有限的Redux知识范围内,我都会得到两种状态。

startReducer.js

import initialState from '../initialState'
import {START} from '../constants/actionTypes'

export default function reducer(state=initialState, action){
  switch (action.type){
    case START:{
      return {...state, started:true}
    }
    default:
      return state
  }
}

reducers / index.js

import {combineReducers} from 'redux';
import start from './startReducer'
import move from './moveReducer'


export default combineReducers({
  move: move,
  start: start
})

App.js

const mapStateToProps = (state) => {
  console.log("state from inside mapStateToProps: ", {...state})
  return {
    //I WANT to just be saying state.currentPlayer... Why two states?
    currentPlayer: state.move.currentPlayer,
    error: state.move.error,
    gameOver: state.move.gameOver,
    moves: state.move.moves,
    started: state.move.started
  }};

这里的问题是,当我控制台日志时

console.log("Full State: ", store.getState())

我明白了:

>move:
  currentPlayer: "white"
  error: null
  gameOver: false
  moves: []
  started: false

>start:
  currentPlayer: "white"
  error: null
  gameOver: false
  moves: []
  started: false

每个简化器的状态为两个副本。如何避免这种情况?在我的体系结构中我做错了什么导致了这种结果?

1 个答案:

答案 0 :(得分:1)

您将立即启动combineReducers(),而无需使用Redux中的createStore()。您需要createStore()才能将所有化简器集中到单个存储/还原状态对象中。

import {createStore, combineReducers} from 'redux';
import start from './startReducer'
import move from './moveReducer'

export default createStore(combineReducers({
  move: move,
  start: start
}))