简体   繁体   English

优化 React 中的功能。 将 setState 键作为道具?

[英]Optimize the function in React. Having setState key as a props?

Having this function, which basically defines which form input to listen to.拥有这个功能,它基本上定义了要收听的表单输入。 However as input is growing, so the function is growing also.然而,随着输入的增长,函数也在增长。

I was thinking about passing an id and compare it with the value of the key of the state so this state will change.我正在考虑传递一个 id 并将其与状态键的值进行比较,这样这个状态就会改变。

onChange = event => {
  if (event.target.id === "Name") {
    this.setState({
      name: event.target.value
    });
  } else if (event.target.id === "Position") {
    this.setState({
      position: event.target.value
    });
  } else if (event.target.id === "Text") {
    this.setState({
      text: event.target.value
    });
  }
};

So how to do it properly with the state?那么如何正确处理状态呢?

I was thinking something like this.我在想这样的事情。 So the input form call the function with the id value and it finds a state with the same name|value.因此输入表单调用具有 id 值的函数并找到具有相同名称|值的状态。

onChange = (event, id) => {
  this.setState({
  { id value as a key?}: event.target.value
  })
}

However, do not understand how to write it correctly.但是,不明白如何正确编写它。 Any help, please?请问有什么帮助吗?

You can do this你可以这样做

onChange = event => {
    this.setState({
        [event.target.id]: event.target.value
    })
}

also change your element id to name , position and text还将您的元素 id 更改为namepositiontext

您更有可能应该使用useReducer

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one

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

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