尝试基于 AsyncStorage React-Native 呈现组件时,对象作为反应子对象无效

objects are not valid as a react child when trying to render component based off of AsyncStorage React-Native

我正在尝试根据 AsyncStorage 的值有条件地呈现组件,但出现上述错误。我什至尝试将对象转换为数组,但效果不佳。不知道还能做什么。

 const test = async () => {
      const test = await ratingCountCompleted;
      let result = Object.values(test);
      result = result.toString();
      console.log(result);

      if(result > 1) {
        console.log('YUP');
        
        return (
          <InAppRating />
        )
      } else {
        console.log('NOPE')
      }
    }

目前正试图通过以下网址帮助您解决此问题:codesandbox,但在 async 处出现奇怪的交互导致了问题。

编辑:我想我发现了问题。 test 函数是异步的并返回错误中指示的承诺:Objects are not valid as a React child (found: [object Promise]).

解决方案:

const [resultState, setResultState] = useState(null);

const test = async () => {
    const test = await ratingCountCompleted;
    let result = Object.values(test);
    result = result.toString();
    console.log(result);

    if (result > 1) {
        console.log("YUP");

        return <Text>Hey</Text>;
    } else {
        console.log("NOPE");
        return null;
    }
};

// setResultState on load
useEffect(() => {
  test().then((component) => setResultState(component));
}, []);

return <View>{resultState}</View>;

我们必须使用 useState 作为我们的初始组件状态,即 null。然后我们用 useEffect 填充它,从 test 获取返回的承诺,最后渲染它。

A second codesandbox to test it

您可以使用条件语句来呈现 o not 元素,如本演示中所示。但是你需要一些状态来触发重新渲染。希望对您有所帮助:

import "./styles.css";
import React from "react";
import { View, Text } from "react-native";

export default function App() {
  const [result, setResult] = React.useState(0);
  const ratingCountCompleted = async () => 2;

  const test = async () => {
    const rating = await ratingCountCompleted();
    setResult(rating);
  };

  React.useEffect(() => {
    test();
  }, []);

  return (
    <div className="App">
      {(result > 1 && (<Text>Yup</Text>)) || (<Text>Nope</Text>)}
    </div>
  );
}

Demo