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