Skip to content

State Updates are Merged #1

@ngminhtrung

Description

@ngminhtrung

Câu hỏi: Phần dưới này có nói đến vụ "the merging is shallow", @hungHoangDang với @duc110789 có hiểu nó là gì không? và nên dịch như thế nào?


When you call setState(), React merges the object you provide into the current state. For example, your state may contain several independent variables:

  constructor(props) {
    super(props);
    this.state = {
      posts: [],
      comments: []
    };
  }

Then you can update them independently with separate setState() calls:

  componentDidMount() {
    fetchPosts().then(response => {
      this.setState({
        posts: response.posts
      });
    });

    fetchComments().then(response => {
      this.setState({
        comments: response.comments
      });
    });
  }

The merging is shallow, so this.setState({comments}) leaves this.state.posts intact, but completely replaces this.state.comments.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions