gpt4 book ai didi

reactjs - Redux : store. getState 返回未定义值

转载 作者:行者123 更新时间:2023-12-03 14:19:00 28 4
gpt4 key购买 nike

为什么我的store.getState返回未定义的值!我对 ReactJS 和 Redux 很陌生,这里是我的代码

import {createStore} from 'redux';

const initialState = {
salary: 1000,
}

const reducer = (state=initialState, action) => {
switch (action.type) {
case "ADD":
state = {
salary: state.salary+=action.payload,
}
break;

default:
break;
}
}

const store = createStore(reducer);

store.subscribe(() => {
console.log('Update salary: ', store.getState.salary);
})

store.dispatch({
type: "ADD",
payload: 2000,
});

控制台:更新工资:-未定义

谢谢。

最佳答案

getState是一个方法,调用它

console.log('Update salary: ', store.getState().salary);

你甚至应该修复你的 reducer

case "ADD":
return {salary: state.salary + action.payload}

它必须返回新状态,您不返回任何内容

关于reactjs - Redux : store. getState 返回未定义值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49220379/

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