V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
ghostgril
V2EX  ›  前端开发

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

  •  
  •   ghostgril · 2018-04-12 14:54:02 +08:00 · 1936 次点击
    这是一个创建于 2199 天前的主题,其中的信息可能已经有所发展或是发生改变。

    网上看到的使用 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 条回复    2018-04-12 15:13:52 +08:00
    ghostgril
        1
    ghostgril  
    OP
       2018-04-12 14:56:09 +08:00
    我在书上看到这段代码,这段代码是为了解释为啥 react 推荐 state 都是不可变的?但是我十分费解,state 不可变的话,那么也变也不会改变把
    ghostgril
        2
    ghostgril  
    OP
       2018-04-12 14:58:04 +08:00
    这里不是调用了 setState 了吗,那么 data 不是变成了新的了?
    ghostgril
        3
    ghostgril  
    OP
       2018-04-12 14:58:35 +08:00
    那么为何里面的 times 不会改变呢
    serco
        4
    serco  
       2018-04-12 15:02:14 +08:00
    @ghostgril
    setState 是异步执行的,所以第三行 console 时 state 还没有更新

    按照你的说法 "react 为何推荐 state 都是不可变", 应该这么理解,react 不推荐直接修改 state 的值,而是需要通过 setState 来修改。所以有时候有人会搭配使用 Immutable,但并不是必须的。
    ghostgril
        5
    ghostgril  
    OP
       2018-04-12 15:13:52 +08:00
    @serco 原来如此
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   928 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 19:56 · PVG 03:56 · LAX 12:56 · JFK 15:56
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.