简体   繁体   English

如何将字符串添加到对象内的字符串值?

[英]How can I add a string to a string value inside an object?

What im trying to do is to add a string id next to a value inside of an object.我试图做的是在对象内部的值旁边添加一个字符串 id。 So the object is like this:所以对象是这样的:

["John","Mike"]

An item in the object is generated as soon the user clicks an add button一旦用户单击添加按钮,就会在对象中生成一个项目

  const handleAddClick = () => {
    setLanguage([...language, ""]);
  };
  const handleItemChanged = (event, index) => {
    const value = event.target.value;
    const list = [...subtitle];
    if (list.filter((f) => f === value).length > 0) {
      setErrorValidation("Names cannot be equal!");
    } else {
      setErrorValidation("");
    }

    list[index] = value;
    setName(list)
  };

In the handleItemChanged, I tried to do this, but it didn't work.在handleItemChanged 中,我尝试这样做,但没有成功。

let string = "test"

list[index] = value + string;
setName(list)

So what I want is to add a string to a new value that is added to the list所以我想要的是将字符串添加到添加到列表中的新值

["Johntest", "Miketest"]

How can I solve this?我该如何解决这个问题?

You can use map before assigning value:您可以在分配值之前使用map

// ... the other code is omitted for the brevity
list.map(item => item + "test") 
setName(list)

An example:一个例子:

 let arr = ["John", "Mike"] arr = arr.map(item => item + " test") console.log(arr)

Calling setName(list) does not trigger a rerender for the simple reason that list is still the same object.调用setName(list)不会触发重新渲染,原因很简单, list仍然是同一个对象。 setState will only work if the previous and new value is different. setState仅在先前值和新值不同时才有效。 For objects, they are shallowly compared.对于对象,它们进行了浅层的比较。

That is why it is suggested to create a new array using .map() :这就是为什么建议使用.map()创建一个新数组的原因:

let string = "test"
const newList = list.map(e => e+urString)
setName(newList)

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

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