我已经实现了useContext+useReducer,并且我发现只有调度发生变化时才会重新呈现.
我可以有两个独立的组件,如果触发了一个调度,则两个组件都会更改.
示例:
每次状态更新时都会呈现递增和递减.
我找到了我关注的这article个,但我仍然得到了同样的结果.
代码:
export default function App() {
return (
<MyContextProvider>
<Count />
<ButtonIncrement /> <br /> <br />
<ButtonDecrement />
</MyContextProvider>
);
}
提供者:
import * as React from 'react';
import {
InitalState,
ApplicationContextDispatch,
ApplicationContextState,
} from './Context';
import { applicationReducer } from './Reducer';
export const MyContextProvider = ({ children }) => {
const [state, dispatch] = React.useReducer(applicationReducer, InitalState);
return (
<ApplicationContextDispatch.Provider value={{ dispatch }}>
<ApplicationContextState.Provider value={{ state }}>
{children}
</ApplicationContextState.Provider>
</ApplicationContextDispatch.Provider>
);
};
上下文:
import React, { Dispatch } from 'react';
export enum ApplicationActions {
increment = 'increment',
decrement = 'decrement',
notification = 'Notification',
}
export type ActionType = ApplicationActions;
export const ActionTypes = { ...ApplicationActions };
export type StateType = {
count: number;
notification: string | undefined;
};
export type Action = {
type: ActionType;
payload?: string | undefined;
};
interface IContextPropsState {
state: StateType;
}
interface IContextPropsDispatch {
dispatch: Dispatch<Action>;
}
export const ApplicationContextState = React.createContext<IContextPropsState>(
{} as IContextPropsState
);
export const ApplicationContextDispatch =
React.createContext<IContextPropsDispatch>({} as IContextPropsDispatch);
export const useApplicationContextState = (): IContextPropsState => {
return React.useContext(ApplicationContextState);
};
export const useApplicationContextDispatch = (): IContextPropsDispatch => {
return React.useContext(ApplicationContextDispatch);
};
export const InitalState: StateType = {
count: 0,
notification: '',
};
异径管:
import { StateType, Action, ActionTypes } from './Context';
export const applicationReducer = (
state: StateType,
action: Action
): StateType => {
const { type } = action;
switch (type) {
case ActionTypes.increment:
return { ...state, count: state.count + 1 };
case ActionTypes.decrement:
return { ...state, count: state.count - 1 };
case ActionTypes.notification:
return { ...state, notification: action.payload };
default:
return state;
}
};
工作示例here
在上面的文章中,这fiddle是作为我try 的一个例子,但我不知道我错在哪里.
请注意,这方面的原始示例没有使用TypeScrip,但在我的try 中,我将添加TypeScrip.