有什么方法可以在 React 中为对象中的键添加另一个值?

Is there any way that I can add another value to a key in an object within React?

我将有一个要在输入字段中输入的对象列表。我让它在创建对象列表的地方工作,但是当我尝试向已经存在的对象之一添加另一个值时。它只会替换其中的先前值。

我console.log()

时的电流输出
const [ tags, setTags ] = useState({
1: 'hello',
2: 'world',
3: 'goodbye'
})

如果第 1 个人添加标签 'testing',我的预期输出。

const [ tags, setTags ] = useState({
1: ['hello', 'testing'],
2: 'world',
3: 'goodbye'
})

我目前使用的函数是从输入中获取值。 A是身份证号,B是新标签。

function updateTags(a, b){

  if(tags.hasOwnProperty(a)){
    setTags((prevTags) => {
      return {
        ...prevTags,
        [a]: ????
      }
    })
  }else{
    setTags((prevTags) => {
      return {
        ...prevTags,
        [a]: b
      }
    })
  }

如果您需要更多信息,请告诉我。

我认为这应该可行

function updateTags(a, b){

  if(tags.hasOwnProperty(a)){
    setTags((prevTags) => {
      return {
        ...prevTags,
        [a]: Array.isArray(prevTags[a]) ? [...prevTags[a], b] : [prevTags[a], b]
      }
    })
  } else {
    setTags((prevTags) => {
      return {
        ...prevTags,
        [a]: b
      }
    })
  }

我认为你可以使用这样的方法:

updateTags = (key, tag) => 
    setTags((prevTags) => ({ 
        ...prevTags,
        [key]: prevTags[key] ? [prevTags[key], tag].flat() : tag,
    }));