Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

javascript - Function inside render and class in reactjs

I'm trying to learn reactjs and i have some uncertainties. I was refering react DOCS and some other tutorials and i saw functions are written inside render function and also inside class. What things should we do inside render function in react?

1st way

class App extends Component {

    test(user) {

        return user.firstName;
    }

    render() {

        const user = {
            firstName: 'Harper',
            lastName: 'Perez'
        };

        return (

            <div>

                <h1>{this.test(user)}</h1>

            </div>
        )
    }
}

2nd way

class App extends Component {

       render() {

        const user = {
            firstName: 'Harper',
            lastName: 'Perez'
        };

        function test(user) {

            return user.firstName;
        }

        return (

            <div>

                <h1>{test(user)}</h1>

            </div>

        )

    }
}

Both this methods work. But i want to know what is the best method to do this? Most importantly i want to know what kind of things i can do inside render function.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The render method normally gets called a lot of times. I think it is more performant to declare your functions outside of the render method if you can. See this answer for a more detailed explanation of the render method.

The test function in your example is a pure function, this allows you to declare it outside the scope/context of the react component altogether as it only needs access to the arguments that are passed in.

That said, it's perfectly fine to declare functions inside a render method or more commonly these days a functional component. There are hooks like useCallback that can help with performance but 99% of the time it's not an issue. Always remember that premature performance optimisation is the roof of all evil and you need to measure performance before you can improve it.

// helpers.js
const test = function(user) {
    return user.firstName;
}

// App.js
const App = () => {
  const user = {
    firstName: 'Harper',
    lastName: 'Perez'
  }

  return (
    <div>
      <h1>hello {test(user)}</h1>
    </div>
  )
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...