bir*_*d03 0 javascript reactjs
我正在阅读React + Redux教程,其中有一个代码片段,如下所示:
class ExampleComponent extends Component {
constructor() {
super();
this.state = {
articles: [
{ title: "React Redux Tutorial for Beginners", id: 1 },
{ title: "Redux e React: cos'è Redux e come usarlo con React", id: 2 }
]
};
}
render() {
const { articles } = this.state;
return <ul>{articles.map(el => <li key={el.id}>{el.title}</li>)}</ul>;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,出于好奇,我做了一个类似的事情,但是在非反应环境中(例如在浏览器的控制台日志中).首先我初始化了constant这样的:
const articles = [
{ title: "React Redux Tutorial for Beginners", id: 1 },
{ title: "Redux e React: cos'è Redux e come usarlo con React", id: 2 }
]
Run Code Online (Sandbox Code Playgroud)
但令我困惑的是destructuring我得到的部分undefined.像这样:
const { someObj } = articles;
undefined
someObj
undefined
{ someObj }
{someObj: undefined}
someObj.title
VM205:1 Uncaught TypeError: Cannot read property 'title' of undefined
at <anonymous>:1:9
Run Code Online (Sandbox Code Playgroud)
我的问题是,为什么const { articles } = this.state;工作正常,但const { someObj } = articles;回报undefined?
你正在以错误的方式尝试.你有一个对象,它有一个数组:
const obj = { arr: [ 1, 2, 3 ] };
Run Code Online (Sandbox Code Playgroud)
而不是使用像obj.arr你那样解构arr:
const { arr } = obj;
Run Code Online (Sandbox Code Playgroud)
并直接使用该变量作为其名称arr.
如果要从数组中解构任何项,可以使用数组destructring:
const [ number1, number2, number3 ] = arr;
Run Code Online (Sandbox Code Playgroud)
如果要组合这些步骤:
const { arr: [ number1, number2, number3 ] } = obj;
Run Code Online (Sandbox Code Playgroud)
因此,右侧是结构化变量,左侧是您从原始变量中解构的变量.另见:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |