0

我正在使用 useReducer 来控制我的 2 个输入:

const [noteInput, setNoteInput] = useReducer(
    (state, newState) => ({ ...state, ...newState }),
    {
      title: '',
      content: ''
    }
  );

在单击按钮后,我希望清除两个输入。useReducer 之后我该怎么做?

4

4 回答 4

0

您可以将名为init的第三个参数传递给 React.useReducer() 。这称为延迟初始化,是恢复到初始状态的快速方法。

https://reactjs.org/docs/hooks-reference.html#lazy-initialization

于 2021-09-03T01:56:44.643 回答
0

如果你只是想使用 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" } 时,在这种情况下,它会将用户名和密码字段重置为空字符串。

https://reactjs.org/docs/hooks-reference.html#usereducer

于 2020-09-16T21:36:05.167 回答
0

您可以使用 setState 将状态更新为空,或者您可以调度其他操作以将该状态更新为空字符串。 https://redux.js.org/basics/reducers#reducers

于 2020-02-17T14:19:13.253 回答
0

如果你有一个 Button,你只需要改变 onSubmit={handleSubmit} 并具有下面的功能,一切都会好起来的。请记住不要设置任何 TextField 的 defaultValue 或您正在使用的内容,只需设置值

const handleReset = (event) => {
    event.preventDefault();
    Object.keys(formInput).forEach((inputKey) => {
        setFormInput({ [inputKey]: '' });
    });
};
于 2021-11-20T14:32:41.277 回答