从ES6箭头函数返回对象文字 [英] Returning Object Literals from ES6 arrow function

查看:124
本文介绍了从ES6箭头函数返回对象文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有人解释为什么在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆