从ES6箭头函数返回对象文字 [英] Returning Object Literals from ES6 arrow function
问题描述
如果有人解释为什么在updatePosts中我们应该返回一个对象,而在对象内部我们应该再次返回它,我将不胜感激.为什么我们只需要做到代码和平=>
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'}))
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屋!