How does React make read-only props?
I'm wondering what mechanism they actually use to throw an error when trying to install this.props.a = 1
or something similar.
I ask because when registering the props, I don't see anything like [Getter/Setter]
that, which I assumed is what they were doing.
Thank!
Good question.
I think that props
is some sort of object value that is marked as const
.
But we can change descendants to any value Object
even if it is marked as const
;
// const also works on objects
const MY_OBJECT = {'key': 'value'};
// Attempting to overwrite the object throws an error - Uncaught TypeError: Assignment to constant variable.
MY_OBJECT = {'OTHER_KEY': 'value'};
// However, object keys are not protected,
// so the following statement is executed without problem
MY_OBJECT.key = 'otherValue'; // Use Object.freeze() to make object immutable
As you can see from the above codes, you can use the Object.freeze () function to make the object immutable.
I think the value is props
set as Object.freeze()
.