我正在使用useReducer来控制我的2个输入:
const [noteInput, setNoteInput] = useReducer(
(state, newState) => ({ ...state, ...newState }),
{
title: '',
content: ''
}
);在onClick on按钮后,我希望两个输入都被清除。在useReducer之后,我该怎么做呢?
发布于 2020-02-17 22:19:13
您可以使用setState将状态更新为empty,也可以分派其他操作将该状态更新为空字符串。https://redux.js.org/basics/reducers#reducers
发布于 2020-09-17 05:36:05
如果您只是想使用useReducer清除表单,您可以使用dispatch来完成此操作。让我们以这个示例按钮组件为例。
//Component
<Button onClick={() => {dispatch({ type: "CLEAR_FORM"})}}>Submit</Button>点击按钮后,"CLEAR_FORM“被分派到减速机。
//Form Initial State & Reducer switch statement
export const initialState={
username:"",
password:""
}
export const reducer = (state, action) => {
switch(action.type){
case: "CLEAR_FORM":
return {
username:"",
password:"",
}
default:
return state
}
} 当reducer获得{ type:"LOG_OUT“}时,在本例中,它将用户名和密码字段重置为空字符串。
发布于 2021-09-03 01:56:45
可以将第三个参数传递给React.useReducer(),名为init。这称为延迟初始化,是恢复到初始状态的一种快速方法。
https://reactjs.org/docs/hooks-reference.html#lazy-initialization
https://stackoverflow.com/questions/60264297
复制相似问题