React Hooks

React推荐我们使用无状态的function式组件,但是在遇见需要使用state或者生命周期的时候不得不使用class式的组件,而React Hooks正是为了解决这个问题

  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的模式

  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传入的是你需要做的操作也就是一个回调函数。

更新中............

原文地址:https://www.cnblogs.com/longlongdan/p/10846291.html