程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了状态更新后不会在 React 组件中重新渲染大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决状态更新后不会在 React 组件中重新渲染?

开发过程中遇到状态更新后不会在 React 组件中重新渲染的问题如何解决?下面主要结合日常开发的经验,给出你关于状态更新后不会在 React 组件中重新渲染的解决方法建议,希望对你解决状态更新后不会在 React 组件中重新渲染有所启发或帮助;

我有一个渲染项,它为每个对象列出一行,并使用 touchableOpacity 的 onPress 方法调用函数并更新状态:

  const renderItem = ({ item }) => (
    <VIEw style={styles.ListItem}>
      <Text style={styles.studentname}>{item.name}</Text>
      <VIEw style={styles.statusSection}>
        <Text style={styles.loginDate}>Last Logged: {new Date(item.loginDate).tolocaleTimeString()}</Text>
        <touchableOpacity onPress={() => updateStudent(item,selectedTab)}>
          <Icon
            name={displayIconname(item.status)}
            type={item.status === 3 ? "entypo" : "Font-awesome"}
            size={30}
            color={item.status === 3 ? "red" : item.status === 1 ? "green" : "gold"}
          />
        </touchableOpacity>
      </VIEw>
    </VIEw>
  );

调用时,状态会正确更新,但 UI 不会重新呈现。当点击其他元素时,UI 会更新到正确的状态,这是应该的,但这里的问题是当状态立即更新时它不会重新呈现:

  function updateStudent(item,tab) {
    let currentStudents = students;
    let studentToUpdate = item;

    const IDx = currentStudents.findindex((value) => {
      return value.uID === item.uID;
    });

    if (studentToUpdate.status === 4) {
      studentToUpdate.status = 0
    } else {
      studentToUpdate.status++
    }

    currentStudents[IDx] = studentToUpdate
    currentStudents.sort((a,b) => { return a.status - b.status })

    console.log(currentStudents === students) // -> Evaluates to True
    setStudents(currentStudents)
  }

这里发生了什么,应该如何修复?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

大佬总结

以上是大佬教程为你收集整理的状态更新后不会在 React 组件中重新渲染全部内容,希望文章能够帮你解决状态更新后不会在 React 组件中重新渲染所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: