1.useReducer

  类似redux的reducer

  使用:

  useReducer(fn,initState)

  接受两个参数,第一个执行函数,有两个参数,state和action

  initState为初始数据

  useReducer返回一个数组,包含state,dispath

  action为判断事件类型,通过dispatch传递

import React, { useReducer } from 'react';

const App = () => {
    const [state, dispath] = useReducer((state, action) => {
        console.log(state);
        switch (action.type) {
            case 'increment':
                return state + 1;
            case 'decrement':
                return state - 1;
            default:
                return state;
        }
    }, 0);

    return (
        <div className='App'>
            <button onClick={() => dispath({ type: 'increment' })}>increment</button>
            <button onClick={() => dispath({ type: 'decrement' })}>decrement</button>
            <p>{state}</p>
        </div>
    );
};

export default App;

 

相关文章:

  • 2022-01-30
  • 2021-12-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-13
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2023-02-06
  • 2021-05-20
  • 2021-08-13
  • 2021-11-08
  • 2022-12-23
相关资源
相似解决方案