最近在学习 React ,发现一些和 Vue 比起来很有趣的区别:
1:更新数据变量
在 Vue 中:
// 变量绑定到元素上:
<div ref="div">{{value}}</div>
// 定义变量:
data() {
return {
value: 0
}
},
// 修改变量:
changeValue() {
this.value = 10;
console.log(this.value); == > 得到结果是 10; 数据变量更新是同步的。
console.log(this.$refs.div.innerText); == > 得到结果是 0, DOM 数据更新是异步的。
}
在 React 中:
// 定义变量:
constructor(props) {
super(props);
this.state = {
value: 0
};
this.changeValue = this.changeValue.bind(this);
};
// 修改变量:
changeValue() {
this.setState({
value: 10
});
console.log(this.state.value); == > 得到结果是 0, 变量的更新是异步的。
};
为了解决他们的异步问题,每个官网都给出了解决方法:
Vue 的解决方法:
changeValue() {
this.value = 10;
this.$nextTick(() => {
console.log(this.$refs.div.innerHTML); == > 得到结果为 10;
})
}
React 的解决方法:
changeValue() {
this.setState({
value: 10
}, () => {
console.log(this.state.value); == > 得到结果为 10;
});
}
目前先写这些,后面可能还会继续补充。