How to destructuring a prop

时间:2019-04-17 02:39:19

标签: javascript reactjs

I'm getting a linter error within my react project regarding destructuring assignment of props, state, and context. The link is here.

I don't understand how I'm supposed to destructure this element.

const { job_id } = props.match.params.job_id;

2 个答案:

答案 0 :(得分:3)

It is probably just

const { job_id } = props.match.params;

Check out the JavaScript object destructuring documentation for more details.

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

console.log(id);

If you need to assign it to a new variable name, you can do this too:

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

console.log(alternative);

答案 1 :(得分:2)

On the right hand side of destructuring assignment there should be the object from which you want to get property.

const { job_id } = props.match.params;

Consider the an object with property prop and prop2.

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