【问题标题】:Mother component controlling input for child components, but doesn't rerender on change母组件控制子组件的输入,但不会在更改时重新呈现
【发布时间】:2020-06-04 08:17:51
【问题描述】:

我有一个 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 对象,因此它不会自动更新。

【问题讨论】:

    标签: javascript reactjs asynchronous state


    【解决方案1】:

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

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

      ,则在过滤器之后使用 slice(-1)[0]
    • 函数 updateLabelValue 改变 globalState。事实上,当您调用 setState 时,您已经更改了 globalState[index] = labelToUpdate 中的状态。

    要解决这个问题,您可以将元素的索引传递给函数并制作类似的东西

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

    【讨论】:

      猜你喜欢
      • 2021-01-26
      • 2021-07-10
      • 2020-06-27
      • 2020-09-14
      • 1970-01-01
      • 1970-01-01
      • 2020-10-19
      • 2020-01-10
      • 1970-01-01
      相关资源
      最近更新 更多