React-useReducer使用
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;