我正在處理一項需要從 API 訪問資料的作業。最近,我看到我的代碼正在努力檢索資料......但是當我嘗試遍歷資料并顯示到我的瀏覽器時......我收到錯誤:
Uncaught (in promise) Error: Objects are not valid as a React child (found: object with keys {common, official, nativeName})。如果您打算渲染一組子項,請改用陣列。
我在 Stack Overflow 上發現了類似的問題……但他們使用 async/await 而不是 fetch 來檢索他們的資料。
有人可以解釋一下我在這里做錯了什么嗎?
代碼如下:
import React, { Component } from "react";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
isLoaded: false,
};
}
// fetches data and sets state which rerenders App
componentDidMount() {
fetch("https://restcountries.com/v3.1/all")
.then((res) => res.json())
.then((json) => {
this.setState({
isLoaded: true,
items: json,
});
});
}
render() {
var { isLoaded, items } = this.state;
if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="App">
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
;
</ul>
</div>
);
}
}
}
uj5u.com熱心網友回復:
實際上 name 屬性也是一個物件。這是其內容的示例。
{common: 'Malta', official: 'Republic of Malta', nativeName: {…}}
在 reactJS 中,你不能渲染這樣的物件。您可以使用例如將其轉換為字串JSON.stringify(myobj)或提取所需的屬性。在這種情況下,您可能應該選擇要顯示的內容,例如:
render() {
var { isLoaded, items } = this.state;
if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="App">
<ul>
{items.map((item) => (
<li key={item.id}>{item.name.common}</li>
))}
;
</ul>
</div>
);
}
}
我還注意到您的 api 可以處理國際化,例如您可以使用react-intl在 react 中處理它。
uj5u.com熱心網友回復:
我認為您要做的是渲染整個物件,您不能這樣做,請嘗試渲染每個元素,我回答的第二部分是您應該使用異步任務,因為您正在使用網路瀏覽器。
希望我的回答能指導你
uj5u.com熱心網友回復:
import React, { Component } from "react";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
isLoaded: false,
};
}
// fetches data and sets state which rerenders App
componentDidMount() {
fetch("https://restcountries.com/v3.1/all")
.then((res) => res.json())
.then((json) => {
console.log(json)
this.setState({
isLoaded: true,
items: json,
}, () => {
console.log("DONE")
});
});
}
render() {
var { isLoaded, items } = this.state;
if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="App">
<ul>
{(items || []).map((item, index) => {
return <li key={index}>{item.name.common}</li>
})}
</ul>
</div>
);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/384281.html
標籤:javascript 反应 接口
