跳到主要内容

语法

2024年02月26日
柏拉文
越努力,越幸运

一、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 useReducer Provider Consumer


const context = createContext({});
const { Provider } = context;

function reducer (state,action){
const { type, payload } = action;

switch(type){
case 'add':
return state = payload;
case 'min':
return state = payload;
default:
return state;
}
}

function Component(){
const { state, dispatch } = useContext();

const handleClick = (dispatch)=>{
dispatch({type: 'add', payload: { ...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 ] = useReducer(reducer, {
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>
}

四、createContext useReducer Provider useContext


const context = createContext({});
const { Provider } = context;

function reducer (state,action){
const { type, payload } = action;

switch(type){
case 'add':
return state = payload;
case 'min':
return state = payload;
default:
return state;
}
}

function Component(){
const { state, dispatch } = useContext();

const handleClick = ()=>{
dispatch({type: 'add', payload: { ...state, a: state.a + 1}});
}

return <div>
<h3> {state.a} </h3>
<button onClick={ handleClick }>改变</button>
</div>
}

function App(){
const [ state, setState ] = useReducer(reducer, {
a: 1,
b: 2
});

return <Provider value={{ state, dispatch: setState }}>
<Component />
</Provider>
}