Function inside rendering and class in reactions

I am trying to find out the reaction, and I have some uncertainties. I referred to the DOCS reaction and some other lessons, and I saw that the functions are written inside the render function, as well as inside the class. What should we do inside the render function in the reaction?

First 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> ) } } 

Second 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 of these methods work. But I want to know what is the best method for this? Most importantly, I want to know what I can do inside the render function.

Thanks.

+5
source share
2 answers

I think this is ultimately your choice, but I personally prefer to only put functions inside the rendering that deal exclusively with the rendering and / or JSX components (i.e. mapping over prop, switch statements that conditionally load the appropriate component based on prop, etc ....). If the logic of the function is heavy, I will leave it from the render.

Here is an example. Say in your component that you have "user" support, which should display a list of users. You may have a rendering 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 have a function that must somehow manipulate user data, it would be better to put this in a function outside the render.

+4
source

The rendering method is usually called many times. I think it's more efficient to declare your functions outside of the rendering method, if you can. See this answer for a more detailed explanation of the rendering method. Since your example is a pure function, you can also declare it as const outside the context of this class.

 const user = { firstName: 'Harper', lastName: 'Perez' } const test = function(user) { return user.firstName; } const App = () => ( <div> <h1>hello {test(user)}</h1> </div> ) 
+2
source

Source: https://habr.com/ru/post/1265124/


All Articles