React Hooks

React推薦咱們使用無狀態的function式組件,可是在碰見須要使用state或者生命週期的時候不得不使用class式的組件,而React Hooks正是爲了解決這個問題react

  1. useState()
    1. 這個函數接收的參數是咱們的狀態初始值(initial state),它返回了一個數組,這個數組的第 [0]項是當前的狀態值,第 [1]項是能夠改變狀態值的方法函數
      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;
    2. setCount( newState )裏面的參數會徹底去替換以前的state
    3. 若是有多種狀態,useState能夠重複調用
      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>
          )
      }
  2. useEffect()
    1. 至關與componentDidMount,componentDidUpdate和componentWillUnmount這些聲明周期函數鉤子的集合體
    2. 參數爲一個function,當組件變化時調用
    3. 能夠傳入第二個參數,爲一個數組,表示只有這個值發生變化的時候才執行
      useEffect(()=>{
              console.log(`you clicked ${count} times`)
          },[count])

      若是傳入一個空數組[],則表示只有首次渲染的時候執行。也就是componentDidMount加componentWillUnmount的模式redux

  3. useReducer()
    1. 接受類型爲 (state, action) => newState 的reducer,並返回與 dispatch 方法配對的當前狀態。
      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;
    2. 當你具備涉及多個子值的複雜狀態邏輯時,useReducer一般優於useState。它還容許你優化觸發深度更新的組件的性能,由於你能夠傳遞調度而不是回調。也就是useReducer是將複雜的邏輯抽象出來放入reducer之中,你只須要傳入一個action便可,而useState傳入的是你須要作的操做也就是一個回調函數。

更新中............數組

相關文章
相關標籤/搜索