封装:
context-manager.js文件:
import React from 'react';
export const MyContext = React.createContext(null);
context封装、自定义函数useboard封装文章来源:https://www.toymoban.com/news/detail-505779.html
import React, { useReducer, useContext } from 'react';
import initState from './state' //state初始状态
const myContext = React.createContext();
const initialState = () => {
return { ...initState }
};
const reducer = (state, action) => {
return { ...state, ...action }
};
const ContextProvider = props => {
const [ state, dispatch ] = useReducer(reducer, {}, initialState);
return (
<myContext.Provider value={{ state, dispatch }}>
{props.children}
</myContext.Provider>
);
};
const useBoard = () => {
const contextValue = useContext(myContext);
return contextValue;
};
export { ContextProvider, useBoard };
state状态存储:文章来源地址https://www.toymoban.com/news/detail-505779.html
const initialState = {
id: '',
}
export default initialState
业务方调用:
import { ContextProvider } from '$context/reducer';
const Board = (props)=>{
return (
<ContextProvider>
<MyBoard props={{ ...props }}/>
</ContextProvider>
)
}
function MyBoard({ props }) {
const { state, dispatch } = useBoard();
console.log('state, dispatch ', state, dispatch)
//...
}
export default Board
// 业务方使用
import React, { useContext } from 'react';
import { MyContext } from '$context/context-manager';
const { id } = useContext(MyContext);
到了这里,关于用context封装状态管理的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!