反应useContext,useRedux子组件不更新

问题描述 投票:1回答:1

反应应用程序中使用挂钩,我使用反应钩useContext,并useReducer模仿终极版然而,当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示例代码

reactjs reducers react-hooks rerender
1个回答
2
投票

你度过了一个第二个参数作为ReactContext函数返回任何内容,因此你看到一个破碎的经验。

的第二个参数createContext是一个功能calculateChangedBits预计将返回一个数字,而不是在文件也许是因为它预计不会被覆盖指定

创设情境像

export const StoreContext = React.createContext(initialState);

作品

Working demo

附:您可以检查calculateChangedBits被如何ReactContext herehere使用

© www.soinside.com 2019 - 2024. All rights reserved.