userContext.js
import { useReducer, createContext } from 'react';
const initState = {
isLogin: false,
user: {
id: 100,
name: 'lucy'
}
}
export const UserContext = createContext();
// action {type: 'LOGIN', payload: true}
const reducer = (state, action) => {
switch(action.type) {
case 'LOGIN':
return {
...state,
isLogin: action.payload,
}
default:
break;
}
}
export const UserProvider = ({children}) => {
// reducer, initState 初始值
const [state, dispatch] = useReducer(reducer, initState);
return (
<UserContext.Provider value={{state, dispatch}}>
{children}
</UserContext.Provider>
)
}
组件使用,index.js
import { UserProvider } from '@/context/userContext'
import App from './App'
export default (props) => {
const [state, setState] = useState()
useEffect(() => {}, [])
return (
<UserProvider>
<App {...props}/>
</UserProvider>
)
}
App.js
import { useContext } from 'react'
import { UserContext } from '@/context/userContext'
function App() {
const {state, dispatch} = useContext(UserContext)
console.log('userContext', state, dispatch)
function onLogin() {
const action = {
type: 'LOGIN',
payload: true
}
dispatch(action)
}
if(!state.isLogin) return (
<Button onClick={onLogin}>登录</Button>
);
return (<div>欢迎,{state.user.name}</div>)
}