![](/img/trans.png)
[英]I can't render the API I fetched with createAsyncThunk when I refresh the page
[英]I can't get the fetched data to render on to the page
我試圖在我的頁面上呈現獲取的數據,但我只能通過 console.log 查看數據並不斷收到此錯誤:
錯誤:元素類型無效:需要一個字符串(對於內置組件)或一個類/函數(對於復合組件)但得到:object。您可能忘記從定義它的文件中導出組件,或者您可能有混淆了默認和命名的導入。
// import StudentContainer from './containers/StudentContainer';
const API = 'https://api.hatchways.io/assessment/students';
class App extends Component {
constructor(props) {
super(props)
this.state = {
allStudents: []
}
}
componentDidMount() {
fetch(API)
.then(resp => resp.json())
.then(students => {
console.log(students.students[0].city)
this.setState({
allStudents: students.students
})
});
}
// <StudentContainer allStudents={allStudents} />
render () {
console.log("state:",this.state)
const { allStudents} = this.state
return (
<div className="App">
{console.log("students:", allStudents[0])}
<h2>Students: {allStudents[0]} </h2>
</div>
)
}
}
export default App;
這個 console.logs 一個 object,里面有鍵值{console.log("students:", allStudents[0])}
但是當我嘗試在頁面上呈現它時,就在底部, <h2>Students: {allStudents[0].city} </h2>
它變得不確定。
這是數據的一個片段:
{city: 'Fushë-Muhurr', company: 'Yadel', email: 'iorton0@imdb.com', firstName: 'Ingaberg', grades: Array(8), …}
city: "Fushë-Muhurr"
company: "Yadel"
email: "iorton0@imdb.com"
firstName: "Ingaberg"
grades: (8) ['78', '100', '92', '86', '89', '88', '91', '87']
id: "1"
lastName: "Orton"
pic: "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/voluptasdictablanditiis.jpg"
skill: "Oracle"```
{allStudents.map((item, i) => (
<div key={i} className="App">
<h2>Students: {item.city} </h2>
</div>
))}
試試這個,我為你測試過它並且有效。
規則是您不能在 UI/HTML 上顯示原始 object。 使用對象的數據創建實際的組件/HTML,或者只是JSON.stringify
它們。
在您的應用程序中,嘗試將帶有<h2>
標記的行更改為: <h2>Students: {JSON.stringify(allStudents[0])} </h2>
另一個問題是您的StudentContainer
組件<> {"studentcontainer:", props.allStudents.map(student => student.city)}</>
的這一行。
一個字符串,然后是一個逗號,然后是一個數組並不是真正有效的 JS。 嘗試將其更改為<pre>{JSON.stringify(props.allStudents.map(student => student.city))}</pre<
並且它至少應該顯示。
(這部分被刪除了,因為 OP 刪除了StudentContainer
組件上的代碼以簡化他的問題,這很好)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.