简体   繁体   English

如何清空输入值并重置 ReactJS 挂钩中的 state

[英]How to empty input values and reset state in ReactJS hooks

Assume I have three inputs and a button, I want to empty input values when button is clicked.假设我有三个输入和一个按钮,我想在单击按钮时清空输入值。

 const [input_value,set_input_value] = useState({
     input1:'',
     input2:'',
     input3:''
 })

const inputs_handler = (e) => {
    let name= e.target.name;
    let value= e.target.value;
    input_value[name] = value;

    set_input_value(input_value);
}

const clear_input_values = () => {

  // First try

    /* 
     set_input_value({
       input1:'',
       input2:'',
        input3:''
     }) 
    */


   //SECOND TRY
    set_input_value(prevState => ({ 
    ...prevState,
        input1:'',
        input2:'',
        input3:''
    }))
  // console.log shows that the values of state didn't get empty from the first click, but does in 
     the second
    console.log(input_value)


}

<div>
  <input onChange={inputs_handler} type='text' name='input1' />
  <input onChange={inputs_handler} type='text' name='input2' />
  <input onChange={inputs_handler} type='text' name='input3' />

  <input onClick={clear_input_values} type='submit' />
</div>

I can use document.getElementsById(id)[0].value='';我可以使用document.getElementsById(id)[0].value=''; to empty the input's value but I don't think this is the proper way to do it in a React project.清空输入的值,但我认为这不是在 React 项目中执行此操作的正确方法。

This is really confusing me, i appreciate if someone provides a clear example or a link to an example that explains how the state works and when it does render the component.这真的让我很困惑,如果有人提供一个清晰的示例或一个示例链接来解释 state 如何工作以及何时渲染组件,我将不胜感激。 since i believe i changed the state value before i use set_inputvalues() method.因为我相信我在使用set_inputvalues()方法之前更改了 state 值。

Issue is state object mutation.问题是 state object 突变。 You are mutating input_value and saving it back in state instead of returning a new object reference.您正在改变input_value并将其保存回 state 而不是返回新的 object 参考。

Updating State更新 State

set_input_value(input_value); vs set_input_value({...input_value, [name]: value }); vs set_input_value({...input_value, [name]: value });

This spreads in the existing state and sets the key-value pair of the input that was updated.这在现有的 state 中传播并设置已更新输入的键值对。

If the spread syntax is unfamiliar it is a common convention to shallowly copy the state object into a new object.如果扩展语法不熟悉,通常的约定是将 state object 浅复制到新的 object 中。 useState hooks can also use functional updates , and if you check the link you'll see a note about how useState doesn't merge in state updates like it's class-based counterpart, this.setState() : useState钩子也可以使用功能更新,如果您检查链接,您会看到有关useState如何不合并到 state 更新中的注释,就像它基于类的对应物this.setState()一样:

Note笔记

Unlike the setState method found in class components, useState does not automatically merge update objects.与 class 组件中的setState方法不同, useState不会自动合并更新对象。 You can replicate this behavior by combining the function updater form with object spread syntax:您可以通过将 function 更新程序表单与 object 扩展语法相结合来复制此行为:

 setState(prevState => { // Object.assign would also work return {...prevState, ...updatedValues}; });

You might notice now that our solution isn't a functional update, but the spread syntax works the same.您现在可能会注意到我们的解决方案不是功能更新,但扩展语法的工作方式相同。 The reason we can do a standard update is because your state consists of 3 independent variables, and upon each update you copy all of them and then simply replace any one of them.我们可以进行标准更新的原因是因为您的 state 包含 3 个独立变量,每次更新时您复制所有变量,然后简单地替换其中任何一个。

Functional updates are primarily used when the next state value depends on the current state value, like the counter examples react loves to use.当下一个state 值取决于当前 state 值时,主要使用功能更新,例如反应喜欢使用的计数器示例。

I should point out that functional updates are a react convention while the spread syntax is part of javascript's expressions & operators .我应该指出,功能更新是一种反应约定,而扩展语法是 javascript 表达式和运算符的一部分。

Clearing Inputs清除输入

Your first try is correct for clearing state, so long as you bind the state value to each input.您的第一次尝试对于清除 state 是正确的,只要您将 state 值绑定到每个输入。

const [input_value, set_input_value] = useState({
  input1: "",
  input2: "",
  input3: ""
});

const inputs_handler = e => {
  let name = e.target.name;
  let value = e.target.value;

  set_input_value({ ...input_value, [name]: value });
};

const clear_input_values = () => {
  set_input_value({
    input1: "",
    input2: "",
    input3: ""
  });
};

return (
  <div className="App">
    <h1>Hello CodeSandbox</h1>
    <h2>Start editing to see some magic happen!</h2>

    <div>
      <input
        onChange={inputs_handler}
        type="text"
        name="input1"
        value={input_value.input1}
      />
      <input
        onChange={inputs_handler}
        type="text"
        name="input2"
        value={input_value.input2}
      />
      <input
        onChange={inputs_handler}
        type="text"
        name="input3"
        value={input_value.input3}
      />

      <input onClick={clear_input_values} type="submit" />
    </div>
  </div>
);

编辑romantic-hawking-rqvko

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM