【问题标题】:How to clear inputs after useReduceruseReducer 后如何清除输入
【发布时间】:2020-06-01 11:52:03
【问题描述】:

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

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

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

【问题讨论】:

    标签: reactjs react-hooks use-reducer


    【解决方案1】:

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

    const handleReset = (event) => {
        event.preventDefault();
        Object.keys(formInput).forEach((inputKey) => {
            setFormInput({ [inputKey]: '' });
        });
    };
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        如果您只是想使用 useReducer 来清除您的表单,您可以使用 dispatch 来完成。让我们以这个示例按钮组件为例。

        //Component
        <Button onClick={() => {dispatch({ type: "CLEAR_FORM"})}}>Submit</Button>
        

        点击“CLEAR_FORM”按钮后,将分派给reducer。

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

        【讨论】:

          【解决方案4】:

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

          【讨论】:

            猜你喜欢
            • 2022-09-27
            • 2020-11-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-09-11
            • 2022-01-18
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多