useState
2025年04月12日
一、createContext useState Provider Consumer
const context = createContext({});
const { Provider, Consumer } = context;
function Component(){
const handleClick = (dispatch)=>{
dispatch({...state, a: state.a + 1});
}
return <Consumer>
{
(value)=>{
return <div>
<h3> {value.a} </h3>
<button onClick={ ()=> handleClick(value.dispatch) }>改变</button>
</div>
}
}
</Consumer>
}
function App(){
const [ state, setState ] = useState({
a: 1,
b: 2
});
return <Provider value={{ state, dispatch: setState }}>
<Component />
</Provider>
}
二、createContext useState Provider useContext
const context = createContext({});
const { Provider } = context;
function Component(){
const { state, dispatch } = useContext();
const handleClick = ()=>{
dispatch({...state, a: state.a + 1});
}
return <div>
<h3> {state.a} </h3>
<button onClick={ handleClick }>改变</button>
</div>
}
function App(){
const [ state, setState ] = useState({
a: 1,
b: 2
});
return <Provider value={{ state, dispatch: setState }}>
<Component />
</Provider>
}