简体   繁体   English

reactjs中的render和class中的函数

[英]Function inside render and class in reactjs

I'm trying to learn reactjs and i have some uncertainties.我正在尝试学习 reactjs,但我有一些不确定性。 I was refering react DOCS and some other tutorials and i saw functions are written inside render function and also inside class.我指的是 react DOCS 和其他一些教程,我看到函数是在渲染函数和类中编写的。 What things should we do inside render function in react?在react中我们应该在render函数内部做什么?

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.谢谢。

The render method normally gets called a lot of times. render 方法通常会被调用很多次。 I think it is more performant to declare your functions outside of the render method if you can.我认为如果可以的话,在 render 方法之外声明你的函数会更高效。 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.您示例中的 test 函数是一个纯函数,这允许您完全在 react 组件的范围/上下文之外声明它,因为它只需要访问传入的参数。

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.有像useCallback这样的钩子可以帮助提高性能,但在 99% 的情况下这不是问题。 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>
  )
}

I think it's ultimately your choice, but I personally prefer only putting functions within render that deal exclusively with rendering components and/or JSX (ie mapping over a prop, switch statements that conditionally load a proper component based on a prop, etc...).我认为这最终是您的选择,但我个人更喜欢只将专门处理渲染组件和/或 JSX 的函数放在 render 中(即映射到 prop、基于 prop 有条件地加载适当组件的 switch 语句等...... )。 If the logic behind the function is heavy, I'll leave it out of render.如果函数背后的逻辑很重,我会把它排除在渲染之外。

Here's an example.这是一个例子。 Say in your component you have a "users" prop that is supposed to display a list of users.假设在您的组件中,您有一个“用户”道具,它应该显示用户列表。 You might have a render function with these types of things:您可能拥有具有以下类型的渲染功能:

 render(){ // An array of user objects & a status string. const { users, status } = this.props; // Map users array to render your children: const renderUserList = () => { return users.map(user => { return <div>{ user.firstName }</div>; }); }; // Conditionally load a component: const renderStatus = () => { let component = ''; switch(status){ case 'loading': component = <Component1 /> break; case 'error': component = <Component2 /> break; case 'success': component = <Component3 /> break; default: break; } return component; } // render() return: return( <div> <div className="status"> { renderStatus() } </div> <div className="user-list"> { renderUserList() } </div> </div> ); }

However, if you had a function that needed to somehow manipulate data about a user, it might be better to put that in a function outside of render.但是,如果您有一个函数需要以某种方式操作有关用户的数据,最好将其放在 render 之外的函数中。

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

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