美文网首页
正确使用setState

正确使用setState

作者: 命题_1f6e | 来源:发表于2020-08-05 11:23 被阅读0次

1. 不要直接修改State

2. state的更新可能是异步的

3. state的更新会合并

正确使⽤setState

setState(partialState, callback)

  1. partialState : object|function
    ⽤于产⽣与当前state合并的⼦集。
  2. callback : function
    state更新之后被调⽤。

不要直接修改 State

// 错误示范
this.state.comment = 'Hello';

// 正确使⽤
this.setState({comment: 'Hello'});

State 的更新可能是异步的

import React, { Component } from "react";
export default class SetStatePage extends Component {
 constructor(props) {
 super(props);
 this.state = {
 counter: 0
 };
 }
 changeValue = v => {
 this.setState({
 counter: this.state.counter + v
 });
 console.log("counter", this.state.counter);
 };
 setCounter = () => {
 this.changeValue(1);
 };
 render() {
 const { counter } = this.state;
 return (
 <div>
 <h3>SetStatePage</h3>
 <button onClick={this.setCounter}>{counter}</button>
 </div>
 );
 }

console.log("counter", this.state.counter); 每次打印的结果都是上一次的,而不是最新的

解决办法
1.在回调中获取状态值

changeValue = v => {
 this.setState(
 {
 counter: this.state.counter + v
 },
 () => {
 console.log("counter", this.state.counter);
 }
 );
};
  1. 使⽤定时器:
setTimeout(() => {
 this.setCounter();
}, 0);
  1. 原⽣事件中修改状态
componentDidMount(){
 document.body.addEventListener('click', this.changeValue, false) }

推荐第一种,第二种可能会多一次dom渲染

State 的更新会被合并

changeValue = v => {
 this.setState({
 counter: this.state.counter + v
 });
};
setCounter = () => {
 this.changeValue(1);
 this.changeValue(2);
};

this.changeValue(2); 会覆盖this.changeValue(1); 最终结果是counter + 2 而不是 + 3

解决办法

changeValue = v => {
 this.setState(state => ({ counter: state.counter + v }));
};
setCounter = () => {
 this.changeValue(1);
 this.changeValue(2);
};

setState第一个参数传一个函数,return { state的属性名: 属性值 }

相关文章

  • 正确使用setState

    1. 不要直接修改State 2. state的更新可能是异步的 3. state的更新会合并 正确使⽤setSt...

  • 正确使用setState

    1、参数 用于产生与当前state合并的子集 state更新后立即执行的回调函数 2、setState更新(异步更...

  • react问题小结(持续更新中)

    React组件会在什么时候render? state使用setState正确改变; props改变,并且符合sho...

  • RN 优化之一

    大组件使用setState ,分离成很小的模块。各用各的setState 把setState 的范围使用到最少。

  • 回调函数里面调用this.setState方法出现以下错误

    简介:React中使用setState出现:TypeError: this.setState is not a f...

  • 08react基础-react原理

    setState()更新数据 setState()更新数据是异步的 注意:使用该语法,后面的setState不要依...

  • React基础知识点总结

    本文目录: 1.React⼊⻔ 2.JSX语法 3.组件 4.正确使用setState 5.⽣命周期 6.组件复合...

  • react_08setState详解

    (一)为什么使用setState? 发现会有警告,并且页面的数字并不会更新。 : 为啥能使用setState方法?...

  • react setState

    正确地使用状态 关于 setState() 这里有三件事情需要知道 不要直接更新状态 例如,此代码不会重新渲染组件...

  • setState的函数用法

    1. this.setState不会立即生效 React中使用this.setState的对象用法时,不会立即改变...

网友评论

      本文标题:正确使用setState

      本文链接:https://www.haomeiwen.com/subject/lhunrktx.html