问题
We create presentational component or stateless component like this
const MyComponent = () => {
return(<div>my component</div>)
}
but I'd seen this
const MyComponent = () =>
<div>
<h1>head</h1>
my component
</div>
so now I'm confused when the braces is needed when using es6's arrow function.
This confused me on when rendering a list using map
shorter version
<div>
{map(o =>
<div>{o.name}</div>
)}
</div>
longer version
<div>
{map(o => {
return(<div>{o.name}</div>)
})}
</div>
Both are correct, but why write longer?
回答1:
{map(o => // without curly brackets
<div>{o.name}</div> // this will be returned implicitly
)}
{map(o => { // with curly brackets
return <div>{o.name}</div> // you need to return explicitly
}
)}
If you do curly brackets , You have to explicilty return the data ,
When to use which one?
When you have mutliple line of execution you need to do curly brackets and return from it
But if you have single line of execution, that you need to return , then there is no need of curly brackets and return , it will return implicitly.
Same as If condition
if(true)
// do this for single line
else
// do this for single line
if() {
// do this for multiple line
} else {
// do this for multiple line
}
回答2:
Arrow functions work both way to provide you with a bit of versatility. Say you need to perform some logic inside your function before you return, in this case you would need to add curly braces, i.e say you need to extract the name of a list of users, but you want to append their title.
let users = [new User(), ... ];
//...
let withTitle = users.map(p => {
const title = getTitle(p); // automagically returns Mr, Mrs, etc
return `${title} ${p.fullName}`
});
// withTitle => ['Mr Ricky Bobby', 'Mr Ron Burgundy']
Now, you can declare a function that does the work for you, and use the shorthand version of the arrow function. like so.
const extractWithTitle: (user) => {
const title = getTitle(p); // automagically returns Mr, Mrs, etc
return `${title} ${p.fullName}`
}
let withTitle = users.map(p => extractWithTitle(p));
// withTitle => ['Mr Ricky Bobby', 'Mr Ron Burgundy']
Now, an even shorter way to approach this would be to pass a reference to the function.
users.map(extractWithTitle);
回答3:
Both are correct, but why write longer?
You basically need to use the longer version if you need to add more sentences in you arrow function other than the jsx component.
E.g.
<div>
{map(o => {
const name = "My name is: " + o.name;
return(<div>{name}</div>)
})}
</div>
Otherwise, you may use the short version.
来源:https://stackoverflow.com/questions/47256739/curly-braces-in-es6-arrow-function-for-each