我在这里学习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/