Why is this.state not directly modified in React, but a new copy is created

Do not modify state. A new copy is created using Object.assign(). Object.assign(state, { visibilityFilter: action.filter }) cannot be used like this because it will change the value of the first parameter. Be sure to set the first parameter to an empty object. You can also use ES7's experimental feature { ...state, ...newState }, refer to the object expansion syntax.

Returns the old state in the default case. When encountering an unknown action, be sure to return to the old state.
It is related to the immutability that React promotes.
In other frameworks such as angular, a variable change is detected through watch and deepwatch. In particular, deepwatch consumes a lot of resources when judging whether a variable with a large amount of data changes, resulting in decreased application performance.

In React, through the principle of "if there is a change, a new object must be returned; if there is no change, the original object will be returned without any change", and changes can always be detected by judging "whether the old and new variables reference the same memory content", Much higher efficiency than deepwatch

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326477835&siteId=291194637