React useContext, useRedux 子组件不更新
React useContext, useRedux child component does not update
使用钩子的 React 应用程序
我正在使用 React Hooks useContext
和 useReducer
来模仿 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
使用钩子的 React 应用程序
我正在使用 React Hooks useContext
和 useReducer
来模仿 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