React useContext, useRedux 子组件不更新

React useContext, useRedux child component does not update

使用钩子的 React 应用程序 我正在使用 React Hooks useContextuseReducer 来模仿 Redux 但是,当更新 Context.Provider 值(计数器)时,子组件不会更新。为什么子组件不重新渲染?

Store.js

import React, {  useReducer } from 'react';
import reducer from '../State/Reducer';
let initialState = {
  count: 99  
};

export const StoreContext = React.createContext(initialState, () => {});

function Store({ children }) {
  const [state, dispatch] = useReducer(reducer, initialState);
  const val = { state, dispatch };
  return <StoreContext.Provider value={val}>{children}</StoreContext.Provider>;
}

export default Store;

Counter.js

import React, {  useContext} from 'react';
import {inc} from '../State/Actions';
import { StoreContext } from './Store';


const Counter = () => {
  const {state,dispatch} = useContext(StoreContext)
  const {count}=state;

  return (
    <div>
      <h1>count: {count}</h1>      
      <button
        type="button"
        onClick={() => {      
          dispatch(inc());          
        }}
      >
        Inc
      </button>
    </div>
  );
};
export default Counter;

我在 CodeSandbox 中有示例代码 https://codesandbox.io/s/github/kyrlouca/react-hooks-counter

您已将第二个参数作为函数传递给 ReactContext,但 return 什么都没有,因此您看到了糟糕的体验。

createContext 的第二个参数是一个函数 calculateChangedBits,它应该是 return 一个数字并且没有在文档中指定可能是因为它不会被覆盖

创建上下文

export const StoreContext = React.createContext(initialState);

有效

Working demo

P.S. You can check how calculateChangedBits being used in ReactContext here and here