Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

javascript - React props: Should I pass the object or its properties? Does it make much difference?

When passing props should I pass the entire object into the child components or should I individually create props first in the parent component and then pass those props to the child?

Pass entire object:

<InnerComponent object={object} />

Individually create props that're needed first:

<InnerComponent name={object.name} image={object.image} />

Which one is preferred and if it depends, what should I use as a gauge to use either?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should prefer your second example, to pass the props individually. There you can see explicitly which arguments are passed and can quickly compare with which arguments are expected. This makes collaboration along people much easier and makes the state of the application more clear.

I personally try to avoid passing whole objects if it's not needed. It's like the spread operator where there can be any property inside and it is much harder to debug in a bigger scope.

Some additions to pure react like prop-types or typescript might help to define clear and expected properties in a big application


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...