天天看點

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
	}
}