【问题标题】:Objects are not valid as a React child (object with keys) React native对象作为 React 子级无效(带有键的对象) React native
【发布时间】:2020-05-30 15:08:40
【问题描述】:

尝试使用 Fetch 显示 Api 数据,想知道如何在返回中只带“品牌”。出现错误“对象作为 React 子级无效:带有键 {all} 的对象。如果您的意思是渲染一组孩子,请改用数组'。

 export default App = () => {
    const [isLoading, setLoading] = useState(true);
    const [data, setData] = useState([]);
    useEffect(() => {
  fetch('https://', {
        method: 'POST',
        timeout: 10000,
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json'
        },

        }) 
    })
        .then((response) => response.json())
     // .then((responseData) => { console.log(responseData); })
       .then((responseData)=> setData(responseData))
        .catch((error) => console.error(error))
        .finally(() => setLoading(false)); [fetch, data];
    }, []);

    return (

<ScrollView>
         <View style= {styles.container}>
            <Text> {data.data}  </Text>
         </View>
         </ScrollView>

我的示例 api 返回值

Object {
  "data": Object {
    "all": Array [
      Object {
        "brand": "A1",
      },
      Object {
        "brand": "B1",
      },
      Object {
        "brand": "C1",

【问题讨论】:

    标签: api react-native


    【解决方案1】:
    export default App = () => {
    const [isLoading, setLoading] = useState(true);
    const [data, setData] = useState([]);
    useEffect(() => {
    fetch('https://', {
        method: 'POST',
        timeout: 10000,
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json'
        },
    
        }) 
    })
        .then((response) => response.json())
     // .then((responseData) => { console.log(responseData); })
       .then((responseData)=> setData(responseData.data))
        .catch((error) => console.error(error))
        .finally(() => setLoading(false)); [fetch, data];
    }, []);
    
    return (
    
        <ScrollView>
         <View style= {styles.container}>
            {data.map((value,index)=>(<Text key={index}>{value.brand}</Text>)}
         </View>
         </ScrollView>
       )
      }
    
    1. 您应该使用映射来访问对象数组。
    2. 您应该添加适当的键以避免副作用。

    【讨论】:

      猜你喜欢
      • 2019-08-18
      • 2022-01-05
      • 1970-01-01
      • 2021-03-08
      • 2018-11-06
      • 2018-12-16
      • 2020-12-28
      • 2020-05-25
      • 2021-06-28
      相关资源
      最近更新 更多