简体   繁体   English

如何防止在 React 类组件中重新渲染/获取数据?

[英]How to prevent re-rendering/fetching data in React Class Component?

I'm working in a music app using React Native, In the Home Screen I make a class component contains more than four FlatList and it's Get data from API "it's large data",我正在使用 React Native 在音乐应用程序中工作,在主屏幕中,我创建了一个包含四个以上 FlatList 的类组件,它从 API 获取数据“这是大数据”,

So i make a function For that, and put it inside componentDidMount(),所以我为此创建了一个函数,并将其放在 componentDidMount() 中,

But I notice when I log the data after setState I see it twice Or more in RN-Debugger但是我注意到当我在 setState 之后记录数据时,我在 RN-Debugger 中看到它两次或更多次

So how can i prevent this happen?那么我怎样才能防止这种情况发生呢? because it's Affected in performance :)因为它会影响性能:)

here's a snippet of my code这是我的代码片段

class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      url: '******',
      loading: false,
      minimal: false,
      MiniURL: '',
      songName: '',
      currentTrackIndex: 0,
      isPlaying: true,
    };
  }
  getRecentSongs = async () => {
    try {
      let response = await API.get('/index');
      let {recent_tracks} = response.data.data;
      let recent_tunes = [];
      recent_tracks.map(track =>
        recent_tunes.push({
          id: track.id,
          name: track.name,
          url: this.state.url + track.sounds,
          img: this.state.url + track.avatar,
        }),
      );
      let data = response.data.data;
      this.setState({data, recent_tunes, loading: true}, () =>
        console.log('data', this.state.data),
      );
    } catch (error) {
      console.log(error);
      this.setState({error: true});
    }
  };
  componentDidMount() {
    this.getRecentSongs();
  }



_renderItem = ({item, index}) => {
    const {url} = this.state;
    return (
      <TouchableNativeFeed
        key={item.id}
        onPress={() => {
          this.props.navigation.navigate({
            key: 'Player',
            routeName: 'Player',
            params: {
              tunes: this.state.recent_tunes,
              currentTrackIndex: index,
            },
          });
        }}
        background={TouchableNativeFeedback.Ripple('white')}
        delayPressIn={0}
        useForeground>
        <Card style={styles.card} noShadow={true}>
          <FastImage
            style={{width: 200, height: 200}}
            source={{uri: url + item.avatar}}
            resizeMode={FastImage.resizeMode.cover}
            style={styles.cardImg}
          />
          <Body style={styles.cardItem}>
            <View style={styles.radioCardName}>
              <View style={styles.cardViewFlex}>
                <Text style={styles.text}>{item.name}</Text>
              </View>
            </View>
          </Body>
        </Card>
      </TouchableNativeFeed>
    );
  };

render(){
  const {data} = this.state;

   return(
        ...
        {/* Recent Songs Here*/}
            <View style={{marginVertical: 10}}>
              <FlatList
                horizontal={true}
                showsHorizontalScrollIndicator={false}
                data={data.recent_tracks}
                contentContainerStyle={{flexGrow: 1}}
                ListEmptyComponent={<EmptyList />}
                keyExtractor={(track, index) => track.id.toString()}
                // initialNumToRender={10}
                renderItem={this._renderItem}
              />
            </View>
     ...
  )
 }

}

It's hard to tell from what's been posted, but is it possible that a key on one of the components is changing more often than you're expecting?从发布的内容中很难判断,但其中一个组件上的键是否有可能比您预期的更频繁地更改? React will trigger a full re-render if it detects any key changes.如果 React 检测到任何关键更改,它将触发完整的重新渲染。

ComponentDidMount will only be executed once and unmounted when it gets deleted. ComponentDidMount 只会执行一次,并在被删除时卸载。 So that means that it is been created twice in some part of your application.所以这意味着它在应用程序的某些部分被创建了两次。

I have encountered a similar problem and it was regarding my navigation library , in my case, I was using react-navigation https://github.com/react-navigation/react-navigation/issues/2599 .我遇到了类似的问题,它与我的导航库有关,就我而言,我使用的是 react-navigation https://github.com/react-navigation/react-navigation/issues/2599

So I can suggest checking if something has happened when your component is created and if it is doing it twice.因此,我建议检查创建组件时是否发生了某些事情,以及它是否执行了两次。 Also, give a double check if your navigation is not doing the same.另外,如果您的导航不一样,请仔细检查。

Please use React.memo请使用React.memo

It will not re-render the component without any relevent data in its props.它不会在其 props 中没有任何相关数据的情况下重新渲染组件。

eg:例如:

/**Your render item*/

const AddsItem = React.memo(({item, index}) => {
   return (
      <TouchableNativeFeed
...
...
</TouchableNativeFeed>
    );
});


/**Your class*/
class Home extends React.Component {
  constructor(props) {
...
}

render(){
  const {data} = this.state;

   return(
...
...
...
)
}

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

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