V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
ghostgril

所谓的 "react 为何推荐 state 都是不可变" 是什么意思呢

  •  
  •   ghostgril · Apr 12, 2018 · 2297 views
    This topic created in 2944 days ago, the information mentioned may be changed or developed.

    网上看到的使用 Immutable 的代码

    getInitialState() { return { data: Map({ times: 0 }) } }, handleAdd() { this.setState({ data: this.state.data.update('times', v => v + 1) }); // 这时的 times 并不会改变 console.log(this.state.data.get('times')); }

    这里说的 times 不会改变值是什么呢?

    5 replies    2018-04-12 15:13:52 +08:00
    ghostgril
        1
    ghostgril  
    OP
       Apr 12, 2018
    我在书上看到这段代码,这段代码是为了解释为啥 react 推荐 state 都是不可变的?但是我十分费解,state 不可变的话,那么也变也不会改变把
    ghostgril
        2
    ghostgril  
    OP
       Apr 12, 2018
    这里不是调用了 setState 了吗,那么 data 不是变成了新的了?
    ghostgril
        3
    ghostgril  
    OP
       Apr 12, 2018
    那么为何里面的 times 不会改变呢
    serco
        4
    serco  
       Apr 12, 2018
    @ghostgril
    setState 是异步执行的,所以第三行 console 时 state 还没有更新

    按照你的说法 "react 为何推荐 state 都是不可变", 应该这么理解,react 不推荐直接修改 state 的值,而是需要通过 setState 来修改。所以有时候有人会搭配使用 Immutable,但并不是必须的。
    ghostgril
        5
    ghostgril  
    OP
       Apr 12, 2018
    @serco 原来如此
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2349 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 10:52 · PVG 18:52 · LAX 03:52 · JFK 06:52
    ♥ Do have faith in what you're doing.