创建上下文context
import React, { useReducer, createContext } from 'react';
import { Counter } from './context';
import { addCount, minusCount, reducer } from './reducers';
/**
* {Provider,Consumer} = createContext(defaultValue)
* defaultValue:只是初始化的值,
* Provider:发布者,value接收的参数个数以及类型要和defaultValue一致
* Consumer:订阅者
*/
/** 当前生成的上下文需要向外暴露给子组件使用 */
export const CountContext = createContext({ text: '', count: 0, count2: 0 });
export default function UseContext() {
/** useReducer的第二个参数就是reducer函数接收的state */
const [state, dispatch] = useReducer(reducer, { count: 0 });
// 为了区分不同的useReducer
const [state2, dispatch2] = useReducer(reducer, { num: 0 });
const initState = 'useReducer+Context的使用'; // initState如果不是字符串,eslint会报错
const providerValue = {
text: initState, //普通参数
count: state.count, //reducer参数
count2: state2.num, //reducer参数
count12: state2.num, //多余的参数无法接收,而且eslint会报错
};
return (
<div>
<br />
<button onClick={() => addCount(dispatch)}>+1</button>
<button onClick={() => minusCount(dispatch2)}>- 1</button>
{/* Provider的value接收的值跟createContext的参数个数以及类型都要一致 */}
<CountContext.Provider value={{ ...providerValue }}>
<Counter></Counter>
</CountContext.Provider>
</div>
);
}
useContext使用
import React, { useContext } from 'react';
import { CountContext } from './index';
export function Counter() {
/** 利用useContext注入父组件的context上下文 */
const { text, count, count2 } = useContext(CountContext);
return <h2>{count + '=>' + text + '<=' + count2}</h2>;
}
reducer
import { ADD, MINUS, TIMES, DIVIDE } from './constant';
export const reducer = (state: any, action: any) => {
switch (action.type) {
case ADD:
return {
...state,
count: state.count + 1
}
break;
case MINUS:
return {
...state,
num: state.num - 1
}
break;
default:
break;
}
}
export const addCount = (dispatch: any) => {
dispatch({
type: ADD,
});
}
export const minusCount = (dispatch: any) => {
dispatch({
type: MINUS,
});
}
网友评论