如何解构道具

问题描述 投票:2回答:2

我在反应项目中遇到了关于道具,状态和上下文的解构分配的错误。链接是here

我不明白我应该如何解构这个元素。

const { job_id } = props.match.params.job_id;
javascript reactjs
2个回答
3
投票

它可能只是

const { job_id } = props.match.params;

查看JavaScript object destructuring documentation了解更多详情。

const o = {id: '5', name: 'Jon'};
const { id } = o;

console.log(id);

如果需要将其分配给新的变量名称,也可以这样做:

const o = {id: '5', name: 'Jon'};
const { id: alternative } = o;

console.log(alternative);

2
投票

在解构赋值的右侧,应该有您想要获得属性的对象。

const { job_id } = props.match.params;

考虑具有属性propprop2的对象。

const obj = { prop: "something", prop2:"string of prop2" }
const { prop } = obj; //get the prop key of the variable 'obj'

console.log(prop); //something

const { prop2 } = obj.prop2 //get the property 'prop2' from the string "string of prop2" which is undefined.

console.log(prop2) //undefined
© www.soinside.com 2019 - 2024. All rights reserved.