javascript – Redux combineReducers没有将状态传递给reducer

前端之家收集整理的这篇文章主要介绍了javascript – Redux combineReducers没有将状态传递给reducer前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在以下代码中,combineReducers不会将数据(状态,操作)传递给reducer.它会在下面生成错误.可能只是我犯的一个小错误.链接到JSFiddle:https://jsfiddle.net/bengrunfeld/1h0t59uf/

import React from 'react'
import { render } from 'react-dom'
import { combineReducers } from 'redux'
import { Constants } from './constants/constants'


const goal = (state = 0,action) => {
  (action.type === Constants.ADD) ?
    state + action.payload:
    state
}

const target = (state = 0,action) => {
  (action.type === Constants.REMOVE)?
    state - action.payload:
    state
}

const reducer = combineReducers({
  goal,target
})

const state = 10

const newState = reducer(state,{
  type: Constants.REMOVE,payload: 5
})

render(
  

错误信息

main.bundle.js:28054 Uncaught Error: Reducer "goal" returned undefined during initialization. If the state passed to the reducer is undefined,you must explicitly return the initial state. The initial state may not be undefined.
    at http://localhost:3000/main.bundle.js:28054:13
    at Array.forEach (native)
    at assertReducerSanity (http://localhost:3000/main.bundle.js:28049:25)
    at combineReducers (http://localhost:3000/main.bundle.js:28104:5)
    at Object.
最佳答案
const Constants = {
  REMOVE: "REMOVE",ADD: "ADD"
}

const goal = (state = 5,action) => {
  return (action.type === Constants.ADD) ?
    state + action.payload:
    state
}

const target = (state = 5,action) => {
  return (action.type === Constants.REMOVE)?
    state - action.payload:
    state
}

const reducer = Redux.combineReducers({
  goal,target
})

const state = {goal: 10,target:5}

const newState = reducer(state,payload: 5
})

console.log(newState);

ReactDOM.render(
  

猜你在找的JavaScript相关文章