gpt4 book ai didi

javascript - 执行 Action 时 redux 出错 : Uncaught type error: cannot read property 'type' of undefined

转载 作者:数据小太阳 更新时间:2023-10-29 04:43:44 25 4
gpt4 key购买 nike

刚刚接触 React。我想这是一个基本问题,但我不明白为什么 reducer 没有被解雇或更新状态:

我的 HomeView.js:

     ....
const { localeChange, counter, locale } = this.props
return (
<div>
<button onClick={() => increment(7)}>Increment</button>
<input type='text' value = {counter}/>
.....
</div>
)

const mapStateToProps = (state) => ({
locale: state.locale,
counter: state.counter
})
export default connect(mapStateToProps, {localeChange, increment})(HomeView)

我的 reducer(常量、action 和 reducer 在同一个文件中):

export const COUNTER_INCREMENT = 'COUNTER_INCREMENT'

export function increment (text) {
return { type: COUNTER_INCREMENT, text }
}

export default function counterIncrement (state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + action.text
default:
return state
}
}

最后是我的“父级”reducer:

import { combineReducers } from 'redux'
import { routeReducer as router } from 'react-router-redux'
import locale from './modules/locale'
import counter from './modules/counter'

export default combineReducers({
locale,
router,
counter
})

我的理解:

在我的状态下,我有一个名为 counter 的字段(它在那里使用 redux 开发工具)。当我单击按钮时,我会发送增量操作,所以我真的应该发送这样的操作:{type: COUNTER_INCREMENT, text: 7}

但是 counterIncrement 函数(reducer)获取未定义的操作:未捕获的类型错误:无法读取未定义的属性“类型”。有什么办法可以正确调试吗?我在 reducer counterIncrement 中放置了一个断点,但没有被触发。

最佳答案

Redux 验证您触发的每个操作实际上都包含一个类型属性。

我的猜测是您正在调用未定义的 dispatch()。您的示例代码不包含任何调度调用,因此我无法提供进一步的帮助 - 但我的猜测是弄清楚这将是微不足道的。要么您调用 dispatch() 时使用了错误的参数,要么您的 action creator 没有返回具有 type 属性的对象。

旁注(与您的问题无关),但您的 action creator 类型标签与 reducer 中的标签不匹配。

关于javascript - 执行 Action 时 redux 出错 : Uncaught type error: cannot read property 'type' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35420710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com