繁体   English   中英

母组件控制子组件的输入,但不会在更改时重新呈现

[英]Mother component controlling input for child components, but doesn't rerender on change

我有一个 React 组件,其中我有一个类别数组,即 map,并从另一个 object 索引数据。


  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}
      />
    )
  })

我传入了 function updateLabelValue ,我尝试更新所选 object 上的特定text属性。

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

 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属性上,所以它会自动更新,但这不会发生

当然,这里的问题是我 map 我的categories ,但访问我的globalState object,因此它不会自动更新。

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

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

  • function updateLabelValue 改变 globalState。 事实上,当您调用 setState 时,您已经在globalState[index] = labelToUpdate中更改了 state。

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

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

暂无
暂无

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

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