首页 > 解决方案 > 母组件控制子组件的输入,但不会在更改时重新呈现

问题描述

我有一个 React 组件,其中有一个类别数组,我映射并索引来自另一个对象的数据。


  const labelComponents = categories.map((category, index) =>{
    const data = globalState.filter(systemLabel => systemLabel.value === category.categoryKey).pop()
    return(
      <Label
      key={data && data.text ? data.text + category : category + index}
      category={category} 
      data={globalState.filter(systemLabel => systemLabel.value === category.categoryKey).pop()}
      deleteLabel={deleteLabel}
      updateLabelValue={updateLabelValue}
      />
    )
  })

我传入了updateLabelValue我尝试更新text所选对象的特定属性的函数。

这个函数可能会被重构,但它现在可以工作。

 const updateLabelValue = (categoryKey, value) =>{
    const labelToUpdate = globalState.filter(entry => entry.value === categoryKey).pop();
    const index = globalState.indexOf(labelToUpdate);
    labelToUpdate.text = value;
    globalState[index] = labelToUpdate
    console.log(globalState)
    setGlobalState(globalState)
  }

我将 euqal 中的密钥放在data.text属性上,所以它会自动更新,但这不会发生

当然,这里的问题是我映射了我的categories,但访问了我的globalState对象,因此它不会自动更新。

标签: javascriptreactjsasynchronousstate

解决方案


你正在改变 React 状态(而 React 根本不喜欢这个)。这可能会引发奇怪的问题,并使事情不会按预期重新渲染。

  • const labelToUpdate = globalState.filter(entry => entry.value === categoryKey).pop(); Pop 是一种可变方法,尽管我不知道在这种情况下是否有问题,因为 filter 纯粹是功能性的。无论如何,如果您只想要一个元素,则可以使用 find 代替 filter ( const labelToUpdate = globalState.find(entry => entry.value === categoryKey)),如果有多个元素并且只想要最后一个 ( const labelToUpdate = globalState.filter(entry => entry.value === categoryKey).slice(-1)[0])

  • 函数 updateLabelValue 改变 globalState。事实上,globalState[index] = labelToUpdate当您调用 setState 时,您已经更改了状态。

要解决此问题,您可以将元素的索引传递给函数并进行类似的操作

 const updateLabelValue = (value, index) =>{
    const newState = globalState.map((item, i) => {
      if(index === i){ return value }
      else{ return item }
    }
    setGlobalState(newState)
  }

推荐阅读