簡體   English   中英

道具更改時反應組件不會重新渲染

[英]React component not re-rendering when props change

我剛剛收到了我的應用程序的錯誤報告,其中undefined undefined正在打印到用戶的屏幕上,他們應該在其中看到名字和姓氏。 仔細想想為什么會這樣,我知道該值在數據庫中始終可用。 因此,我認為問題在於,在極少數情況下,屏幕可能會在所有數據可用之前加載。 我在用? 處理 null 檢查以避免錯誤,但從技術上講,這可能會導致頁面在數據可用之前加載。

我的問題是雙重的,基於我將要分享的代碼,如果值在第一頁加載時不可用,是否會在值到達時自動重新渲染屏幕? 如果不是,那么處理這種情況的更好方法是什么?

這是我的相關代碼:

import React from 'react';
import {
  Text,
  View,
  Image,
} from 'react-native';

import moment from "moment";
import componentStyles from './styles';

import { statusCodeToIcon, statusCodeToText, visitTypeToText } from '../../lib/VisitUtils';

export class VisitItem extends React.PureComponent {
  render() {
    const { item, screenType } = this.props;

    return (
      <View style={componentStyles.sectionContainer}>
        <View style={componentStyles.visitItemContainer}>
          <Image
            style={componentStyles.visitIcon}
            source={statusCodeToIcon(item?.status?.value)}
          />
          
          <View style={componentStyles.flexColumn}>
            <Text style={componentStyles.largeText}>{visitTypeToText(item?.type?.value)}</Text>
            { 
              screenType && screenType === 'detailsReview' ?
              <Text style={componentStyles.mediumText}>
                {`${item?.name?.first?.value} ${item?.name?.last?.value}`}
              </Text> : null
            }
            <Text style={componentStyles.mediumText}>{statusCodeToText(item?.status?.value)}</Text>
            <Text style={componentStyles.mediumText}>{moment(item?.date?.value).format('MMM Do YYYY')}</Text>
          </View>
        </View>
        <View style={componentStyles.horizontalBorderLight} />
      </View>
    );
  }
}
 

根據關於純組件的React 文檔

React.PureComponent 類似於 React.Component。 它們之間的區別在於 React.Component 沒有實現 shouldComponentUpdate(),但是 React.PureComponent 實現了一個 shallow prop 和 state 比較。

React.PureComponent 的 shouldComponentUpdate() 僅淺比較對象。 如果這些包含復雜的數據結構,它可能會產生更深層差異的假陰性。 僅當您希望擁有簡單的道具和 state 時才擴展 PureComponent ,或者當您知道深層數據結構已更改時使用 forceUpdate() 。 或者,考慮使用不可變對象來促進嵌套數據的快速比較。

此外,React.PureComponent 的 shouldComponentUpdate() 會跳過整個組件子樹的 prop 更新。 確保所有子組件也是“純”的。

鑒於您的道具更改很深,純組件淺層比較似乎無法檢測到更改並重新渲染。

嘗試擴展React.Component

暫無
暫無

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

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