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
  }};

这里的问题是,当我安装log

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

每个还原器的我状态的两个副本。我该如何避免这种情况?我在以这种方式结束我的架构中做错了什么?

您在不使用Redux的createStore()的情况下立即启动combineReducers()。您需要createStore()将所有还原器集中到一个单数商店/Redux-State对象中。

import {createStore, combineReducers} from 'redux';
import start from './startReducer'
import move from './moveReducer'
export default createStore(combineReducers({
  move: move,
  start: start
}))

最新更新