React functions inside render()

前端 未结 2 1637
醉梦人生
醉梦人生 2020-12-01 15:45

Is there a preference on where you put functions inside a react component. I am still learning react so just trying to figure out the best practices.

class          


        
2条回答
  •  眼角桃花
    2020-12-01 16:20

    It's worth pointing out that there are times when you want to perform intensive calculations in the render() and take the performance hit. Especially when it involves making calculations from props. Take the case of

    class Person extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          name: props.firstName + props.lastName,
        };
      }
    
      render() {
        return 
    {this.state.name}
    ; } }

    Now when props changes, the state won't be updated as the constructor function only runs when the component is mounted. A better way would be to make the calculation in render. So whenever your component rerenders, it recalculates and renders the right value.

    class Person extends React.Component {
      render() {
        const myName = this.props.firstName + this.props.lastName;
    
        return 
    {myName}
    ; } }

    And this version is a bit cleaner to read:

    class Person extends React.Component {
      calculateName = () => {
        return this.props.firstName + this.props.lastName;
      }
    
      render() {
        const myName = this.calculateName();
    
        return 
    {myName}
    ; } }

提交回复
热议问题