从 ES6 箭头函数返回对象文字 [英] Returning Object Literals from ES6 arrow function
问题描述
如果有人解释为什么在 updatedPosts 中我们应该返回一个对象,而在一个对象内部我们应该再次返回它,我将不胜感激?为什么我们可以只用代码来代替 =>
I will be appreciated if someone explains why in updatedPosts we should return an object and inside an object we should return it again? why can we just do this peace of code instead =>
const updatedPosts = posts.map(data =>{...数据,作者:《狮子座》})
const updatedPosts = posts.map(data => { ...data, author : 'Leo' } )
class Blog extends Component {
state = {
post : []
}
componentDidMount(){
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
const posts = response.data.slice(0,3);
const updatedPosts = posts.map(data =>{
return {
...data,
author : 'Leo'
}
})
this.setState({post : updatedPosts})
console.log(response)
})
推荐答案
这段代码 const updatedPosts = posts.map(data => { ...data, author : 'Leo' } )
实际上是可能的,但你必须在给你的对象周围加上括号
This piece of code const updatedPosts = posts.map(data => { ...data, author : 'Leo' } )
is actually possible but you have to put parenthesis around the object which gives you
const updatedPosts = posts.map(data => ({ ...data, author : 'Leo' }))
您可以在本文档的返回对象文字部分找到解释https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
You can find the explanation in the Returning Object Literals section of this documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
这篇关于从 ES6 箭头函数返回对象文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!