React报错:Invariant violation,对象无法作为React子元素问题求助
Hey, let's break this down clearly. That error message is a dead giveaway—your tt variable isn't the plain array you think it is. Those _40/_65/_55/_72 keys are internal state properties of a Promise object (common in React Native's Promise implementation). React can't render Promises directly, which is why you're hitting this invariant violation.
First, verify this is the issue
Add a quick console log to check what tt actually is:
console.log("Type of tt:", typeof tt, "\nValue:", tt);
If the output shows it's an object with Promise-related properties, that confirms the problem.
How to fix it
The fix depends on where tt is coming from:
If
ttis from an async request (like fetch/axios)
In React/React Native, you need to manage async data with state. UseuseEffect(for functional components) orcomponentDidMount(for class components) to fetch and resolve the data before rendering:Functional component example:
import { useState, useEffect } from 'react'; import { View, Text } from 'react-native'; function YourComponent() { // Initialize state as an empty array const [data, setData] = useState([]); useEffect(() => { // Wrap async logic in a function const fetchData = async () => { // Replace this with your actual API call const response = await fetch('your-api-endpoint'); const resolvedData = await response.json(); // Update state with the resolved array setData(resolvedData); }; fetchData(); }, []); // Empty dependency array means this runs once on mount // Render the data once it's available return ( <View> {data.map((item) => ( <View key={item.infinite}> <Text>{item.sub}</Text> </View> ))} </View> ); }If
ttis supposed to be a static array
Double-check your code to make sure you didn't accidentally overwritettwith a Promise. For example, if you wrote something likett = fetchMyData()(wherefetchMyDatais async), you'd be assigning a Promise tottinstead of the resolved array.
What about that {...item} solution you saw?
That's a shorthand for passing all properties of an object as props to a child component, like this:
// Child component that accepts a "sub" prop function ListItem({ sub }) { return <Text>{sub}</Text>; } // Parent component rendering the list return data.map((item) => ( <View key={item.infinite}> <ListItem {...item} /> {/* Passes all item properties as props to ListItem */} </View> ));
This is just a cleaner way to pass props—it has nothing to do with your current error. Your problem is rooted in the fact that you're trying to render a Promise instead of a resolved array.
内容的提问来源于stack exchange,提问作者Olli

