How does React make read-only props?
1 answer
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()
.
0
source to share