首页 > 编程知识 正文

react 数据更新,react怎么更新数据

时间:2023-05-03 12:12:46 阅读:283546 作者:3824

最近在学习 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;});}

目前先写这些,后面可能还会继续补充

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。