使用useState
第1步:引入useState
import React,{ useState} from 'react';
第2步:获取useState中的数据
const App = ()=>{let [value,setValue] = useState('hello')//修改的函数const update = ()=>{setValue('world')}return (<div>{value}<button onClick={update}>修改</button></div>)
}
使用useEffect
第1步:引入useEffect
import React,{ useEffect } from 'react';
第2步:使用useEffect函数
const App = ()=>{let [value,setValue] = useState('hello')//修改的函数const update = ()=>{setValue('world')}//useEffect函数作为生命周期函数使用useEffect(()=>{console.log('useEffect....')})return (<div>{value}<button onClick={update}>修改</button></div>)
}
使用useReducer
import React,{ useState, useEffect, useLayoutEffect, useReducer } from 'react';
import ReactDOM from 'react-dom';const defaultState = {value: "hello"
}const reducer = (state,action)=>{if(action.type === 'update'){let copyState = JSON.parse(JSON.stringify(state))copyState.value = action.valuereturn copyState}return state
}const App = ()=>{let [state,dispatch] = useReducer(reducer,defaultState)const handleUpdate = ()=>{let action = {type: 'update',value: 'world'}dispatch(action)}return (<div><button onClick={handleUpdate}>修改</button>{ state.value }</div>)
}ReactDOM.render(<App />,document.getElementById('root'));
操作useContext
import React,{ useState, createContext, useContext } from 'react';
import ReactDOM from 'react-dom';//1、创建Context上下文对象
const Context = createContext()//2、声明根组件APP
const App = ()=>{let [value,setValue] = useState(0)//3、在APP组件中需要使用 Context.Provider 管理上下文对象中的数据return (<Context.Provider value={{value,setValue}}><div><Father></Father></div></Context.Provider>)
}//4、声明父组件,在父组件中获取 Context 上下文对象中的数据
const Father = ()=>{let {value,setValue} = useContext(Context)const add = ()=>{setValue(value+1)}return (<div>Father组件:{value} <button onClick={add}>父组件中修改</button><Child></Child></div>)
}//5、声明子组件,在组件中获取 Context 上下文对象的数据
const Child = ()=>{let {value,setValue} = useContext(Context)const add = ()=>{setValue(value+1)}return (<div>Child组件:{value} <button onClick={add}>子组件中修改</button></div>)
}ReactDOM.render(<App />,document.getElementById('root'));