反応フック- usestateとusereducerカンニングペーパー- Redux


私は理解するのに苦労していたuseReducer 私はreduxの背景を持っていないので.それで、私はそれを自分自身に説明するためにこの記事を書きました.

学びuseState ファースト
あなたが知っているならばuseState 次に、このセクションをスキップすることができますuseReducer to useState .
useStatereactjs.org )

  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
const [count, setCount] = useState(0);
  • useState(0) : 初期状態(この場合は0)を渡し、2要素の配列を返します.count and setCount .
  • count : 新国家
  • setCount : 状態値を変更する関数.如しthis.setState() クラスベースのコンポーネントです.

  • 比較するuseReducer useReducer 複雑に使われるstate 状況
    たとえば、カウンタを減らすためにもう一つのボタンを加えたいです.
    使用するコードはこちらuseState useStatereactjs.org )
     const [count, setCount] = useState(0);
    
      return (
        <div>
          {count}
          <button onClick={() => setCount(count + 1)}>
            +
          </button>
          <button onClick={() => setCount(count - 1)}>
            -
          </button>
        </div>
      );
    }
    
    我々は移動する予定ですcount+1 and count -1FUNCTION 使用によってuseReducer
    const [count, setCount] = useReducer(FUNCTION, {count: 0})
    
    インuseReducer , コールcount ASstate , setCount ASdispatch , and FUNCTION is reducerこのように見えます.
    const [state, dispatch] = useReducer(reducer, {count: 0})
    
    MDN かなりよく説明しますArray.prototype.reduce() そうです.それはあなたが何であるかuseReducer .

    次に、減速器機能を書きますreducer function パラメータ2パス
    function reducer(state, action) {
      switch (action.type) {
        case 'increment':
          return {count: state.count + 1};
        case 'decrement':
          return {count: state.count - 1};
        default:
          throw new Error();
      }
    }
    
    state : 現状action : 状態を変更したい場合はdispatch関数を呼び出します.この場合、最初の要素はtype , 参照action.type .
    例えば、私は呼ぶdispatch({type: 'increment'}) , then count は+ 1になります.
    <button onClick={() => dispatch({type: 'decrement'})}>-</button>
    <button onClick={() => dispatch({type: 'increment'})}>+</button>
    
    完全なコード
    function reducer(state, action) {
      switch (action.type) {
        case 'increment':
          return {count: state.count + 1};
        case 'decrement':
          return {count: state.count - 1};
        default:
          throw new Error();
      }
    }
    
    function Counter() {
      const [state, dispatch] = useReducer(reducer, {count: 0});
      return (
          {state.count}
          <button onClick={() => dispatch({type: 'decrement'})}>-</button>
          <button onClick={() => dispatch({type: 'increment'})}>+</button>
        </>
      );
    }
    
    それはあなたを助ける希望!❤️