React functions inside render()

前端 未结 2 1621
醉梦人生
醉梦人生 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 <div> {this.state.name} </div>;
      }
    }
    

    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 <div> {myName} </div>;
      }
    }
    

    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 <div> {myName} </div>;
      }
    }
    
    0 讨论(0)
  • 2020-12-01 16:29

    A function in the render method will be created each render which is a slight performance hit. It's also messy if you put them in the render, which is a much bigger reason, you shouldn't have to scroll through code in render to see the html output. Always put them on the class instead.

    For stateless components, it's probably best to keep functions outside of the main function and pass in props instead, otherwise the function will be created each render too. I haven't tested performance so I don't know if this is a micro-optimization but it's worth noting.

    Example:

    const MyStatelessComponent = ({randomProp}) => (
        render() {
            doSomething(randomProp);
    
            return <div />
        }
    );
    
    doSomething = (randomProp) => {
        //Do something here
    }
    
    0 讨论(0)
提交回复
热议问题