【问题标题】:State update doesn't trigger rerender in conditional rendering component状态更新不会触发条件渲染组件中的重新渲染
【发布时间】:2020-08-18 00:16:20
【问题描述】:

我的组件大致是这样的:

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 提取的用于我的本机应用程序的辅助钩子,因此它有一点延迟。 当我运行它时,我看到控制台日志“数据未准备好”,然后是“数据准备好”,但我只看到 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 无关的事情。但只是想把它放在这里。

【问题讨论】:

  • 你能用帮助代码编辑线程吗
  • 当然,会编辑!

标签: reactjs react-native react-hooks conditional-operator conditional-rendering


【解决方案1】:

首先,由于自定义挂钩中的 key 参数未定义,因此永远不会设置数据。将密钥作为道具传递给自定义钩子。

其次,您需要更新条件以检查数据是否存在,假设 ready 属性在设置后的数据上存在,如下所示:

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 />
        </>
    )
}

【讨论】:

  • 抱歉,我最初并没有计划放置实际的挂钩代码,所以我没有填写正确的调用,但在我的实际代码中,我确实将密钥传递给了自定义挂钩。我继续添加刚才的数据检查并获得相同的行为。我将编辑问题以反映正确的钩子调用,很好!
  • 另外,控制台日志是正确的,所以我认为数据被正确检索,只是没有重新渲染
  • 能否也分享一下populateStoredValue函数
  • 这里也包括日志
  • 填充存储值函数在我共享的代码中(在钩子内定义)。日志是“数据未准备好”,然后是“数据准备好”。
猜你喜欢
  • 2019-06-17
  • 2019-05-07
  • 2020-07-26
  • 2021-05-19
  • 2022-01-26
  • 1970-01-01
  • 2018-06-05
  • 2023-03-09
  • 2019-06-29
相关资源
最近更新 更多