簡體   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