Javascript 以对象为参数的箭头函数是什么意思?
What does Javascript Arrow function with object as parameter mean?
我在这里学习 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 shorthand for
this.setState({items: items})
和
({results: items})
基本上接受一个对象作为带有属性命名结果的参数,并且在函数体中它被映射到items
运行 通过转译器,例如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 页面上保留一个 link - 如果有任何 ES6 代码让您感到困惑,请将其粘贴到那里以查看 ES5 版本是什么 :p 那是我的秘籍
我在这里学习 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 shorthand for
this.setState({items: items})
和
({results: items})
基本上接受一个对象作为带有属性命名结果的参数,并且在函数体中它被映射到items
运行 通过转译器,例如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 页面上保留一个 link - 如果有任何 ES6 代码让您感到困惑,请将其粘贴到那里以查看 ES5 版本是什么 :p 那是我的秘籍