在 React 中使用 Context 和 Reducers 实现 Redux 功能无法正常工作

Implementing Redux functionality using Context and Reducers in React not working Properly

所以我正在尝试仅使用反应钩子来实现 redux 的功能,如以下链接所示 https://codeburst.io/global-state-with-react-hooks-and-context-api-87019cc4f2cf & https://www.sitepoint.com/replace-redux-react-hooks-context-api/ 但由于某种原因我似乎无法让它正常工作。我正在尝试实现一个基本设置,其中 DO_ACTION 操作在单击按钮时被调度并且计数器全局状态显示在按钮下方。当我点击几次后点击增量操作按钮时,由于某种原因我得到了未定义。我在这里做错了什么?

点击前

点击 3 或 4 次后

这是我的文件夹结构,以防你认为我导入了错误的东西

按钮组件

import './Button.css';
import React, {useEffect, useContext} from 'react';
import {Context} from '../../store/Store.js';

const Button = ( props ) => {

const [state, dispatch] = useContext(Context);

const incrementAction = () => {
    dispatch({
        type:'DO_ACTION',
        payload: 1
    })
    console.log(state.number);
  };

return (
    <div>
        <button onClick={() => incrementAction()}>Display Number!!!!</button>
        <div>{state.number}</div>
    </div>
    )
};

export default Button

这是我的减速器

const Reducer = (state, action) => {
switch (action.type) {
    case 'DO_ACTION':
        return state + action.payload
    }
};

export default Reducer;

这是我的全球商店和 HOC

import React, {createContext, useReducer} from "react";
import Reducer from './Reducer';


const initialState = {
    number: 5
};

const Store = ({children}) => {
    const [state, dispatch] = useReducer(Reducer, initialState);
    
    return (
        <Context.Provider value={[state, dispatch]}>
            {children}
        </Context.Provider>
    )
};

export const Context = createContext(initialState);
export default Store;

这是我的主要 App 组件,它用商店包裹起来,可以在我的整个应用程序中访问它

import Store from './store/Store.js';
import Button from './components/Button/Button.js';

const App = () => {

    return (
        <div>
          <Store>
            <Button />
            <OtherComponents /> //a bunch of other components go here like title, paging etc
          </Store>
        </div>
    );
}

export default App;

您需要从 reducer 函数返回整个(克隆的)状态对象,而不仅仅是要更新的 属性。您还应该确保您有一个默认大小写:

const Reducer = (state, action) => {
    switch (action.type) {
        case 'DO_ACTION':
            return {
                number: state.number + action.payload
            }
        default:
            return state;
    }
};

export default Reducer;

如果您的状态对象中有多个 属性,您必须记得将所有其他属性也克隆到其中(例如 {...state, number: state.number + action.payload})。