javascript - 以对象为参数的 JavaScript 箭头函数是什么意思?

标签 javascript reactjs ecmascript-6 arrow-functions

我在这里学习ReactJS: https://egghead.io/lessons/react-dynamically-generated-components并发现了这个代码片段:

componentWillMount(){
    fetch( 'http://swapi.co/api/people/?format=json')
        .then( response => response.json() )
        .then( ({results: items}) => this.setState({items}) )
}

({results: items}) 是什么意思?部分箭头函数是什么意思?

我见过箭头函数

  • 不带参数()=>console.log('hi')
  • 不带括号word=>console.log(word)
  • 并且多个参数以逗号分隔(one, two)=>console.log(one)

但绝不是这样的对象字面量。

另外,为什么this.setState({items}) items 周围需要大括号?这一切意味着什么?

最佳答案

this.setState({items})

是 ES6 的简写

this.setState({items: items})

({results: items}) 

基本上接受一个对象作为参数,其属性名为 results,并在函数体内映射到项目

通过转译器运行,例如babel try it out repl page你的代码

fetch( 'http://swapi.co/api/people/?format=json')
    .then( response => response.json() )
    .then( ({results: items}) => this.setState({items}) )

变成了

var _this = this;

fetch('http://swapi.co/api/people/?format=json')
.then(function (response) {
    return response.json();
})
.then(function (_ref) {
    var items = _ref.results;
    return _this.setState({ items: items });
});

我建议保留该 babel 页面的链接 - 如果任何 ES6 代码让您感到困惑,请将其粘贴到那里以查看 ES5 版本是什么:p 这是我的作弊

关于javascript - 以对象为参数的 JavaScript 箭头函数是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41689020/

相关文章:

javascript - Next.js,重定向到getServerSideProps里面的404页面

javascript - es6 类中的属性验证

javascript - 生成对象的属性访问

javascript - 使用参数变量获取传递给 ES6 箭头函数的参数

performance - 有什么方法可以在开发模式下禁用或加速 React PropType 验证吗?

javascript - 事件监听器看不到 div#id 元素,也不与它合作

javascript - 在直接链接之前通过 javascript/jquery 清空 PHP session 变量

javascript - 将 JQuery 上下文 $(this) 传递给另一个函数并检索上下文数据

javascript - 在 redux 中更新数组时如何避免状态变化

javascript - MaterializeCss 模态报错 openModal is not a function