簡體   English   中英

ReactJS:當調用 render() 中的 function 時,組件的內容不會更新

[英]ReactJS: Contents of a component not updating when a function inside render() is called

我正在努力實現某些目標,但我不確定這是最好的方法:

我有一個顯示在<ProductDisplay />組件內的產品數組 (productArray)。 我還有一個<FilterPanel /> ,它允許我對 productArray 中的元素進行排序。 <ProductDisplay /><FilterPanel />都包含在一個名為<MainContainer />的 hoc 中,其樣式如下:

<MainContainer>
    <FilterPanel />
    <ProductDisplay />
</MainContainer>

<MainContainer />在它的 render() 方法中有一個排序 function。 排序 function 被傳遞給<FilterPanel /> ,當被調用時,它對 productArray 進行排序。 排序后的 productArray 從<MainContainer />傳遞到<ProductDisplay />

這是<MainContainer />的簡化代碼:

//import sorting functions: categorySort, timeSort, and ratingSort

class MainContainer extends Component {

  constructor(props) {
    super(props)

    this.state = {
      sort: ""
    }
  }

  render() {
    const { productArray } = this.props; //getting an array of products from props

    let sortResult = productArray; //if no sorting selected, sortResult will be the default order
  
    const performSort = (sortType) => {
      this.setState({sort: `${sortType}`}); //not really important

      switch(sortType) {
        case 'time':
          sortResult = timeSort(productArray); //gets sorted when called
          break;
        case 'category':
          sortResult = categorySort(productArray); //gets sorted when called
          break;
        case 'rating':
          sortResult = ratingSort(productArray); //gets sorted when called
        break;
        default:
          console.log('default case')
      }
    }

    console.log( `sortResult final`);
    console.log(sortResult);        //does not reflect sorting done above; still in initial state

    return (
      <div>
          <FilterPanel performSort={performSort}/>
          <ProductDisplay sortResult = {sortResult} />
      </div>
    );
  }
}

當從<FilterPanel />調用排序 function 'performSort' 時,它成功地在 switch 語句中生成了一個排序的 'sortResult' 數組,但是,switch 語句之外(之后)的 'sortResult' 沒有改變(並且正在向下傳遞<ProductDisplay />不變)。 這很奇怪,因為 'sortResult' 應該在 switch 語句的 scope 內。

非常感謝任何幫助解決這個問題(另外,任何關於如何做得更好的建議。請注意,我還沒有學習鈎子,所以我更喜歡沒有鈎子的解決方案)。

React 組件僅在其傳入的 props 更改、state 更改或它們使用的上下文更改時重新渲染。 (或者,在 React 路由器中,當 URL 發生變化時。)這個基本事實是理解 React 的關鍵部分。

在這種情況下,您正在更改 Javascript 變量......但不是我提到的三(四)件事之一。

要解決這個問題,您可以將sortResult作為setState的一部分(即this.state.sortResult ),然后在完成排序后設置它。 因為這改變 state,它會導致你的組件重新渲染,並從你返回的 JSX 生成新的 DOM。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM