infinite Render in React

后端 未结 3 1972
隐瞒了意图╮
隐瞒了意图╮ 2020-12-20 22:17

I am having problem figuring out why my application is doing endless render.

Inside, My stateful component, I am calling a redux action in componentDidMount method (

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-20 22:51

    There are some points to note in your code.

    • The CoinCard Component must be a PureComponent, which will not re-render if the props are shallow-equal.
    • You should not render your Flatlist inside the ScrollView component, which would make the component render all components inside it at once which may cause more looping between the Flatlist and ScrollView.
    • You can also a definite height to the rendered component to reduce the number of times component is rendered for other props.
    • Another thing to note is, only props in the component are rendered on scroll bottom, based on the log statement mentioned below.

      import {Dimensions} from 'react-native'
      
      const {width, height} = Dimensions.get('window)
      
      class CoinCard extends React.PureComponent {
      render () { 
        console.log(this.props.item.long)  //... Check the prop changes here, pass the item prop in parent Flatlist. This logs component prop changes which will show that same items are not being re-rendered but new items are being called.
        return (
           //... Render 10 items on the screen
            
              Text
            
          
        )  
       }
      }
      

    UPDATE

    This extra logging is due to the props being from the Flatlist to your component without PureComponent shallow comparison.

    Note that componentWillReceiveProps() is deprecated and you should avoid them in your code. React.PureComponent works under the hood and uses shouldComponentUpdate to use shallow comparison between the current and updated props. Therefore log console.log(this.props.item.long) in your PureComponent' render will log the unique list which can be checked.

提交回复
热议问题