在条件渲染组件中,状态更新不会触发重新渲染。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在条件渲染组件中,状态更新不会触发重新渲染。相关的知识,希望对你有一定的参考价值。

我的组件大致是这样的。

import useCustomHook from "./hooks";

const Test = () => {
    const [data, setData] = useCustomHook("example-key", {ready: false});
    return (
        data.ready ?
        <>
            {console.log("data is ready");}
            <ComponentA />
        </> :
        <>
            {console.log("data is not ready");}
            <ComponentB />
        </>
    )
}

useCustomHook 是一个帮助钩,从 AsyncStorage 为我的本地应用程序,所以它有一点延迟。当我运行这个程序时,我看到控制台记录 "data is not ready"(数据未准备好),然后是 "data is ready"(数据准备好),但我只看到ComponentB渲染,而从未看到ComponentA。

如果有帮助的话,自定义钩子是这样的。它基本上只是将JSON序列化成一个字符串进行存储。

export default (key, initialValue) => {
  const [storedValue, setStoredValue] = React.useState(initialValue);

  React.useEffect(() => {
    const populateStoredValue = async () => {
      const storedData = await AsyncStorage.getItem(key);
      if (storedData !== null) {
        setStoredValue(JSON.parse(storedData))
      }
    }
    populateStoredValue()
  }, [initialValue, key]);

  const setValue = async (value) => {
    const valueToStore = value instanceof Function ? value(storedValue) : value;
    await AsyncStorage.setItem(key, JSON.stringify(valueToStore));
    setStoredValue(valueToStore);
  }

  return [storedValue, setValue];
}

有谁知道这里可能发生了什么?

谢谢!

小PS:我也看到了警告 Sending "onAnimatedValueUpdate" with no listeners registered.,这似乎是一个 react-navigation 不相关的事情。但就是想把这个放在这里。

答案

首先,作为你的 钥匙 param在自定义钩子中是未定义的,所以数据永远不会被设置。将键作为道具传递给自定义钩子。

其次,你需要更新你的条件来检查数据是否存在,假设是 妥当 设置后的数据存在属性,就像这样。

import useCustomHook from "./hooks";

const Test = () => {
    const [data, setData] = useCustomHook(/* Add key here */);
    return (
        data && data.ready ?
        <>
            console.log("data is ready");
            <ComponentA />
        </> :
        <>
            console.log("data is not ready");
            <ComponentB />
        </>
    )
}

以上是关于在条件渲染组件中,状态更新不会触发重新渲染。的主要内容,如果未能解决你的问题,请参考以下文章

尽管状态发生了变化,但自定义钩子不会触发组件重新渲染

Vuex 全局状态更改不会触发 Nuxt 中 v-for 循环中的重新渲染组件

Vue 组件 prop 更改不会触发重新渲染

高阶组件状态正在正确更新,但接收道具的包装组件不会在状态更改时重新渲染

React Native 和 Redux:为啥子组件不会在每次状态更新时重新渲染?

使用 Lodash.remove 通过 Vuex 突变更改状态不会触发我的 Vue 组件中的反应式重新渲染