美文网首页
useReducer(了解)

useReducer(了解)

作者: 未路过 | 来源:发表于2022-11-02 10:11 被阅读0次
image.png

如果state中有复杂的逻辑的话

import React, { memo, useState } from "react";

const App = memo(() => {
  const [count, setCount] = useState(0);
  return (
    <div>
      <h2>当前计数:{count}</h2>
      <button onClick={(e) => setCount(count + 1)}>+1</button>
      <button onClick={(e) => setCount(count - 1)}>-1</button>
      <button onClick={(e) => setCount(count + 5)}>+5</button>
      <button onClick={(e) => setCount(count - 5)}>-5</button>
      <button onClick={(e) => setCount(count + 100)}>+100</button>
    </div>
  );
});

export default App;

不适用useState,使用useReducer

import React, { memo, useReducer } from "react";

function reducer(state, action) {
  const { data, type } = action;
  switch (type) {
    case "increment":
      return { ...state, count: state.count + 1 };

    case "decrement":
      return { ...state, count: state.count - 1 };

    case "add_number":
      return { ...state, count: state.count + data };

    case "sub_number":
      return { ...state, count: state.count - data };
    default:
      return state;
  }
}

const App = memo(() => {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <div>
      <h2>当前计数:{state.count}</h2>
      <button onClick={(e) => dispatch({ type: "increment", data: 1 })}>
        +1
      </button>
      <button onClick={(e) => dispatch({ type: "decrement", data: 1 })}>
        -1
      </button>
      <button onClick={(e) => dispatch({ type: "add_number", data: 5 })}>
        +5
      </button>
      <button onClick={(e) => dispatch({ type: "sub_number", data: 5 })}>
        -5
      </button>
      <button onClick={(e) => dispatch({ type: "add_number", data: 100 })}>
        +100
      </button>
    </div>
  );
});

export default App;

当点击加或者减的时候,本质是派发事件,就来到reducer函数,对事件进行处理,返回一个新的state,state发生改变,整个App组件就会重新执行,重新执行useReducer,拿到新的reducer,继而拿到新的状态。重新渲染jsx。

优点

管理非常复杂的数据的时候使用。
比如state里面有
{ counter: 0, friends: [], user: {} }
需要管理。
如果使用useState的化,需要定义三次
const [counter, setCounter] = useState(0)
const [friends, setFriends] = useState([])
const [user, setUser] = useState({})
使用useReducer的化,就只用定义一次。

const [state, dispatch] = 
useReducer(reducer, { counter: 0, friends: [], user: {} })

然后在functionreducer(state, action)里面的switch里面统一做修改。

总结:数据复杂,操作复杂,就放到reducer里面,在reducer里面执行所有的逻辑。用的很少,因为想改变数据,就要到reducer里面来,某种程度上不是很方便。一般不使用reducer。

相关文章

网友评论

      本文标题:useReducer(了解)

      本文链接:https://www.haomeiwen.com/subject/nsnstdtx.html