反应应用程序中使用挂钩,我使用反应钩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示例代码
你度过了一个第二个参数作为ReactContext
函数返回任何内容,因此你看到一个破碎的经验。
的第二个参数createContext
是一个功能calculateChangedBits
预计将返回一个数字,而不是在文件也许是因为它预计不会被覆盖指定
创设情境像
export const StoreContext = React.createContext(initialState);
作品