我正在使用 useReducer 来控制我的 2 个输入:
const [noteInput, setNoteInput] = useReducer(
(state, newState) => ({ ...state, ...newState }),
{
title: '',
content: ''
}
);
在单击按钮后,我希望清除两个输入。useReducer 之后我该怎么做?
我正在使用 useReducer 来控制我的 2 个输入:
const [noteInput, setNoteInput] = useReducer(
(state, newState) => ({ ...state, ...newState }),
{
title: '',
content: ''
}
);
在单击按钮后,我希望清除两个输入。useReducer 之后我该怎么做?
您可以将名为init的第三个参数传递给 React.useReducer() 。这称为延迟初始化,是恢复到初始状态的快速方法。
https://reactjs.org/docs/hooks-reference.html#lazy-initialization
如果你只是想使用 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" } 时,在这种情况下,它会将用户名和密码字段重置为空字符串。
您可以使用 setState 将状态更新为空,或者您可以调度其他操作以将该状态更新为空字符串。 https://redux.js.org/basics/reducers#reducers
如果你有一个 Button,你只需要改变 onSubmit={handleSubmit} 并具有下面的功能,一切都会好起来的。请记住不要设置任何 TextField 的 defaultValue 或您正在使用的内容,只需设置值
const handleReset = (event) => {
event.preventDefault();
Object.keys(formInput).forEach((inputKey) => {
setFormInput({ [inputKey]: '' });
});
};