Why can vue get the latest value immediately after assigning data directly, while React gets the old value after setData and the new value after render?

for example:

// vue
new Vue({
    data() {
        return {
            data: 1
        }
    },
    methods: {
        handleClick() {
            this.data = 100
            console.log(this.data) //  100
        }
    }
})
// react
class Test extends React.Component {
  constructor(props) {
    super(props)
    this.state = { data: 10 }
  }

  handleClick() {
    this.setState({data: 100})
    console.log(this.state.data) //  10
  }

  render() {
    return (
      <button onClick={this.handleClick}></button>
    );
  }
}
Sep.28,2021

the two treat data differently
vue is a way of hijacking data and notifying subscriptions, so you can respond to changes in data immediately.
react data update setState is asynchronous

this.setState({data: 100}, () => {
  console.log(this.state.data) //  100
})

both are rendered asynchronously. The design of Vue is that the modifications of Model are made by Synchronize, then record the changes to the queue, accumulate a certain period and then render View;React. The reason why View;React does not do this is to achieve Slice, that is, concurrent updates. The rendering process of a component can be suspended many times to make room for more important tasks.

on the other hand, even if state modifies Synchronize, props must be known only after the parent component is updated. Vue is a Push mechanism, and you can accurately respond to updates through hijacking, while React is not easy to do, so in order to avoid confusion (and avoid repeated rendering), it is reasonable to keep state and props Synchronize.

the callback of setState ensures that the new value is obtained.


as said upstairs, react's setState is asynchronous, sometimes you don't understand, it's really hard to play with.

so setState overloads a callback way to get the value after the state update.

react actually updates state in batches to improve performance.

Menu