Redux/Reducer - 调度不改变状态
Redux/Reducer - dispatching doesnt change state
正如标题所说,我发送了一个动作,但我的状态没有改变。这是一些代码:
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",
console.log('TEST)
来自 reducer.js
打印 'TEST' 但 state name
保持不变。
console.log(store.name)
来自 app.js 打印 undefined
知道为什么这不起作用吗?
您应该使用 store.getState()
访问当前状态。
store.getState().name
应该是 return 这个名字。由于 store
没有 name
属性,undefined
是 returned.
store.dispatch({ type: TEST })
console.log(store.getState().name)
正如标题所说,我发送了一个动作,但我的状态没有改变。这是一些代码:
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",
console.log('TEST)
来自reducer.js
打印 'TEST' 但state name
保持不变。console.log(store.name)
来自 app.js 打印undefined
知道为什么这不起作用吗?
您应该使用 store.getState()
访问当前状态。
store.getState().name
应该是 return 这个名字。由于 store
没有 name
属性,undefined
是 returned.
store.dispatch({ type: TEST })
console.log(store.getState().name)