简体   繁体   English

State 更新不会触发条件渲染组件中的重新渲染

[英]State update doesn't trigger rerender in conditional rendering component

My component roughly looks like this:我的组件大致如下所示:

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 is helper hook that pulls from AsyncStorage for my native application, so it has a slight delay. useCustomHook是从AsyncStorage为我的本机应用程序提取的辅助钩子,因此它有一点延迟。 When I run this, I see the console logs "data is not ready" followed by "data is ready", but I only see ComponentB render, and never ComponentA.当我运行它时,我看到控制台日志“数据未准备好”,然后是“数据准备好”,但我只看到 ComponentB 渲染,而从来没有看到 ComponentA。

If it's helpful, the custom hook looks like this.如果有帮助,自定义钩子看起来像这样。 It basically just serializes the JSON into a string for storage.它基本上只是将 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];
}

Anyone have ideas on what might be happening here?有人对这里可能发生的事情有想法吗?

Thanks!谢谢!

small PS: I also see the warning Sending "onAnimatedValueUpdate" with no listeners registered.小 PS:我还看到警告Sending "onAnimatedValueUpdate" with no listeners registered. , which seems like it's a react-navigation thing that's unrelated. ,这似乎是一个不相关的react-navigation事情。 But just wanted to put that here.但只是想把它放在这里。

First of all, as your key param in custom hook is undefined so data will never be set.首先,由于您在自定义挂钩中的关键参数未定义,因此永远不会设置数据。 Pass the key to the custom hook as the prop.将密钥作为道具传递给自定义钩子。

Secondly, you need to update your condition to check if data is present or not, assuming ready property exist on data after set, like this:其次,您需要更新您的条件以检查数据是否存在,假设设置后数据上存在就绪属性,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM