天天看点

React-Hooks的useReducer()钩子

基本使用

const [state, dispatch] = useReducer(reducer, initialState)
// useReducer接受reducer函数和状态的初始值作为参数,返回一个数组,数组第一个元素是状态的当前值,数组的第二个元素是发送action的dispatch函数
           

举例:

const [state, dispatch] = useReducer(reducer, {value : 0})

<button onClick={()=> dispatch({type: 1})}>点击+1</button>

// reducer函数     state参数为initialState即{value : 0}    action为{type: 1}
const reducer=(state,action)=>{
	if(action.type === 1){
		return {
		state:...state,
		value:state.value+1
		}
	}else{
		return state
	}
}