react中useReducer

661 阅读1分钟

useReduce

他是useState的代替方案,它接受一个存函数(state,action) =>newState的reducer并返回当前的 state 以及与其配套的 dispatch 方法。

const [state, dispatch] = useReducer(reducer, initialArg, init);

如果一个传入useState一个值是对象,对象里面嵌套对象的话,修改里面的某个一个值会麻烦,这时用useReducer可以很好的解决这个问题。

import React,{useReducer} from 'react'

const initValue = {
   count:0
}
const reducer = (state =initValue,action) =>{
 switch (action.type) {
    case "add":
      return { ...state, count: state.count + action.count };
    case "minus":
      return { ...state, count: state.count - action.count };
    default:
      return state;
  }
}
const Reducer = () => {
  const [state, dispatch] = useReducer(reducer, initValue);
  useEffect(
    () => {
      console.log(state);
    },
    [state]
  );
  return (
    <div>
      <p>
        count的值:{state.count}
      </p>
      <button onClick={() => dispatch({ type: "add", count: 1 })}>+</button>
      <br />
      <button onClick={() => dispatch({ type: "minus", count: 1 })}>-</button>
    </div>
  );
};

export default Reducer;