对象作为 React 子对象(带键的对象)React 本机无效



尝试使用 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",
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. 您应该添加适当的键作为响应,以避免副作用。

最新更新