React推薦咱們使用無狀態的function式組件,可是在碰見須要使用state或者生命週期的時候不得不使用class式的組件,而React Hooks正是爲了解決這個問題react
import React,{ useState } from 'react' function Counter(props) { const [count, setCount] = useState(0); return ( <div> {count} <button onClick={()=>{ setCount(count + 1) }}>+</button> </div> ) } export default Counter;
function Counter(props) { const [count, setCount] = useState(0); const [obj, setObj] = useState({name: "lili"}); return ( <div> {count} <button onClick={()=>{ setCount(count + 1) }}>+</button> {obj.name} <button onClick={()=>{ setObj({name: "didi"}) }}>+</button> </div> ) }
useEffect(()=>{
console.log(`you clicked ${count} times`)
},[count])
若是傳入一個空數組[],則表示只有首次渲染的時候執行。也就是componentDidMount加componentWillUnmount的模式redux
import React, { useReducer } from 'react' import reducer from './reducer/1.reducer' //counter是另外一個計數器,只需傳入對應的值即可以與當前計數器共享一個redux狀態 import Counter from './components/1.counter' function App(props) { //建立redux,並獲取到state&&dispatch const [state, dispatch] = useReducer(reducer, 0); return(<div> {"計數器1:"+state} <button onClick={()=>dispatch({type: 'increment'})}>+</button> <button onClick={()=>dispatch({type: 'decrement'})}>-</button> <Counter state={state} dispatch={dispatch}/> </div>) } export default App;
useReducer
一般優於useState
。它還容許你優化觸發深度更新的組件的性能,由於你能夠傳遞調度而不是回調。也就是useReducer是將複雜的邏輯抽象出來放入reducer之中,你只須要傳入一個action便可,而useState傳入的是你須要作的操做也就是一個回調函數。更新中............數組