【发布时间】:2021-03-17 00:09:57
【问题描述】:
正如标题所说,我发送了一个动作,但我的状态没有改变。这是一些代码:
App.js
import { createStore } from 'redux'
import reducer from './../reducer/reducer'
import { TEST } from './../reducer/actions'
// Initial store
const initialStore = {
name: "John",
count: 0
};
const store = createStore(reducer, initialStore);
store.dispatch({ type: TEST })
console.log(store.name);
Reducer.js
import { GET_ITEMS, ADD_ITEM, TEST } from './actions'
function reducer (state, action) {
console.log(state, action);
if(action.type === TEST){
console.log("TEST");
return {...state, name: "Mark"};
}
return state;
}
export default reducer;
package.json
"react-redux": "^7.2.2",
"redux": "^4.0.5",
-
来自
reducer.js的console.log('TEST)打印出“TEST”,但state name保持不变。 -
console.log(store.name)来自 app.js 打印undefined
任何想法为什么这不起作用?
【问题讨论】:
-
你应该使用 store.getState() 来获取 store 的当前值。
-
@udeepshrestha 没错!谢谢!我正在观看的教程没有使用 .getState() 但无论哪种方式都有效。不知道怎么做。