【问题标题】:React useContext, useRedux child component does not updateReact useContext,useRedux子组件不更新
【发布时间】:2019-06-21 06:34:34
【问题描述】:

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

【问题讨论】:

    标签: reactjs reducers react-hooks rerender


    【解决方案1】:

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

    createContext 的第二个参数是一个函数 calculateChangedBits,它预计会返回一个数字,但文档中未指定可能是因为它不会被覆盖

    创建类似的上下文

    export const StoreContext = React.createContext(initialState);
    

    作品

    Working demo

    附:您可以查看calculateChangedBits 是如何在ReactContext herehere 中使用的

    【讨论】:

    • 谢谢,确实是这个问题。我尝试对传递给 Provider 的对象使用相同的签名
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 2020-06-12
    • 2019-06-19
    • 2018-10-09
    • 2019-04-29
    • 2017-05-10
    相关资源
    最近更新 更多