[英]Functions are not valid as a react child? - Need help to extract fetched data into table
我的家庭作業項目的快速摘要。
我的后端有一個REST API,該API具有從外部API返回《星球大戰》角色的API方法。
在我的Web開發中,我試圖從我的REST API中獲取這些數據,並且可以看到這些數據實際上顯示在瀏覽器開發人員工具中,但是又出現了另一個錯誤。
“警告:index.js:1437警告:函數作為React子代無效。如果您返回Component而不是從render返回,則可能會發生這種情況。或者您可能打算調用此函數而不是返回它。”
您能否在下面的.js文件中看到問題所在?
import React, {Component} from "react";
import {Table,} from 'react-bootstrap'
const urlCharacters = 'URL WORKS - BUT NOT SHOWING HERE.';
class Characters extends Component {
constructor(props) {
super(props);
this.state = {characters: []}
;
}
async componentDidMount() {
//async fetchCharactersFromBackend(){
const res = await fetch(urlCharacters);
const data = await res.json();
console.log(data);
const newData = data.map(e => JSON.parse(e.name));
this.setState([newData]);
}
render() {
if (!this.state.characters) {
return null
}
return (
<div>
<h2>Persons table</h2>
<Table striped bordered hover>
<thead>
<tr>
<th>Character Name</th>
</tr>
</thead>
<tbody>
{this.renderCharacters}
</tbody>
</Table>;
</div>
);
}
renderCharacters(characters) {
characters.forEach(e => {
return ("<tr><td>" + e.name + "</td></tr>")
});
}
}
/*
Persons = () => {
return (
<div>
<h2>Persons table</h2>
<Table striped bordered hover>
<thead>
<tr>
<th>Character Name</th>
</tr>
</thead>
<tbody>
{this.renderCharacters}
</tbody>
</Table>;
</div>
);
};
*/
export default Characters;
做以下修復,讓我知道它是否有效:
this.setState([newData]); --> this.setState({characters: newData})
{this.renderCharacters} --> {this.renderCharacters()}
將renderCharacters更新為以下內容:
renderCharacters() {
return this.state.characters.map(e => {
return ("<tr><td>" + e.name + "</td></tr>")
});
}
}
{this.renderCharacters}
應該
{this.renderCharacters()}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.