【问题标题】:Redux/Reducer - dispatching doesnt change stateRedux/Reducer - 调度不会改变状态
【发布时间】: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.jsconsole.log('TEST) 打印出“TEST”,但state name 保持不变。
  • console.log(store.name) 来自 app.js 打印 undefined

任何想法为什么这不起作用?

【问题讨论】:

  • 你应该使用 store.getState() 来获取 store 的当前值。
  • @udeepshrestha 没错!谢谢!我正在观看的教程没有使用 .getState() 但无论哪种方式都有效。不知道怎么做。

标签: reactjs redux reducers


【解决方案1】:

您应该使用store.getState() 访问当前状态。 store.getState().name 应该返回名称。由于store 没有name 属性,因此返回undefined

store.dispatch({ type: TEST })
console.log(store.getState().name)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-20
    • 2016-09-27
    • 2018-08-09
    • 2023-03-23
    • 2019-01-30
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    相关资源
    最近更新 更多