反应useContext,useRedux子组件不会更新

时间:2019-01-28 09:28:21

标签: reactjs reducers react-hooks rerender

使用挂钩反应应用程序 我正在使用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

1 个答案:

答案 0 :(得分:2)

您已将第二个参数传递给ReactContext作为函数,该函数不返回任何内容,因此您会感到不愉快。

createContext的第二个参数是函数calculateChangedBits,该函数应返回一个数字,并且未在文档中指定,也许是因为它不希望被覆盖

创建类似上下文

export const StoreContext = React.createContext(initialState);

有效

Working demo

  

P.S。您可以检查calculateChangedBits herehere

ReactContext的使用方式