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

奇怪的 bug。setState 更新 state 之后并没有重新 render 出来正确的值。

  •  
  •   lbfeng · 2018-05-10 11:07:00 +08:00 · 4336 次点击
    这是一个创建于 2149 天前的主题,其中的信息可能已经有所发展或是发生改变。

    Link: https://gitlab.com/alex1007/react-test.git

    input 里输入名字或者邮箱返回 match 的结果。前几个返回的值即使在 setState 之后也不会消失。

    https://gitlab.com/alex1007/react-test/raw/master/shot.png

    3 条回复    2018-05-11 23:26:42 +08:00
    maichael
        1
    maichael  
       2018-05-10 11:27:57 +08:00   ❤️ 2
    你的 Contact 子组件写的有问题,直接取 props 就好,为什么存到 state 里。

    子组件的 state 从来没变过。
    lbfeng
        2
    lbfeng  
    OP
       2018-05-11 23:20:49 +08:00
    @maichael 因为要高亮 keyword 所以还是需要在 constructor 里初始化。getDerivedStateFromProps 解决了 bug

    https://stackoverflow.com/questions/41233458/react-child-component-not-updating-after-parent-state-change?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

    const contacts = this.state.result.map((contact, i) =>
    <Contact contact={contact} key={i} keyword={this.state.query} />);
    console.log(contacts);

    我的问题是 contacts 这个 array 已经变了,问什么还是有之前的会显示。
    lbfeng
        3
    lbfeng  
    OP
       2018-05-11 23:26:42 +08:00
    @maichael 我知道了,一开始有 array 里有 1000 个值,有 1000 个 Contact 被 mount,keyword 变化时 array 的长度变了。多余的被 unmount,剩下的不变,虽然的有新的 props 但因为没有 getDerivedStateFromProps,所以也没被更新。不知道想的对不对。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1003 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 19:27 · PVG 03:27 · LAX 12:27 · JFK 15:27
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.