加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React之组件state的正确打开方式

发布时间:2020-12-15 07:14:04 所属栏目:百科 来源:网络整理
导读:setState是改变React组件中state值的唯一方法,不能直接对state赋值: class Dog extends Component { constructor(props) { super(props) this.state = { color: 'white',age: 7,son: { color: 'gray',age: 1 } } } brushHair() { //right setState({color:

setState是改变React组件中state值的唯一方法,不能直接对state赋值:

class Dog extends Component {
    constructor(props) {
        super(props)
        this.state = {
            color: 'white',age: 7,son: {
              color: 'gray',age: 1
            }
        }
    }
    
    brushHair() {
      //right
      setState({color: 'black'})
      
      //wrong
      this.state.color = 'black';
    }
}

state的更新可能是异步的,不要依赖当前state的值去计算下一个state

addAge() {
    //wrong
    setState({age: ++this.state.age})
}

正确的写法是使用setState的另一种用法,即参数可以是一个函数:

addAge() {
    setState((prevState,props) => ({
        age: ++prevState.age
    }))
}

当更新state的部分属性时,其他属性是不会受影响的,但仅限于第一层结构

brushSonHair() {
    setState({
        son: {
            color: 'black'
        }
    })
}

上面的方法中setState改变的时第二层的属性值(son中的color),第一层的属性值(color age)不会受到影响,但son中的age属性就会丢失(可以理解为改变了son)。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读