Reactjs 使用React在引导表上呈现API时出现问题
我是一个新手,我正在尝试呈现一个API,但它在每个端点创建新表,我认为问题在于我正在映射,但我不知道还能做什么 提前谢谢你的帮助 我是否应该为表创建一个新组件Reactjs 使用React在引导表上呈现API时出现问题,reactjs,api,fetch,Reactjs,Api,Fetch,我是一个新手,我正在尝试呈现一个API,但它在每个端点创建新表,我认为问题在于我正在映射,但我不知道还能做什么 提前谢谢你的帮助 我是否应该为表创建一个新组件 class App extends Component { constructor() { super(); this.state = {}; } componentDidMount() { fetch(url) .then(results => { return
class App extends Component {
constructor() {
super();
this.state = {};
}
componentDidMount() {
fetch(url)
.then(results => {
return results.json();
})
.then(data => {
let coins = data.map(coin => {
return(
<div>
<Table striped bordered hover variant="dark">
<thead>
<tr>
<th>#</th>
<th>Sign</th>
<th>Name</th>
<th>Market Cap</th>
<th>Price</th>
<th>Change 24h</th>
<th>Buy</th>
</tr>
</thead>
<tbody>
<tr>
<td>{coin.market_cap_rank}</td>
<td>{coin.symbol}</td>
<td>{coin.name}</td>
<td>{coin.market_cap}</td>
<td>{coin.current_price}</td>
<td>gerfds</td>
<td>@mdo</td>
</tr>
</tbody>
</Table>
</div>
)
});
this.setState({ coins: coins });
});
}
render() {
return (
<div className="container">
<HeadJumbotron />
<div className="container2">{this.state.coins}</div>
</div>
);
}
}
你是个新手,总是试着阅读文档,尤其是在组件生命周期中,你似乎不理解它。您可能会在代码中遇到一些错误,因为我不知道您的api返回了什么。但您的代码应该是这样的
class App extends Component {
constructor() {
super();
this.state = {
// i am asumming you are returning data
data : [];
};
}
componentDidMount() {
fetch(url)
.then(results => {
//return results.json(); get the data from here and set it to state here. am assuming is called data
this.setState({
data:results.data
})
})
}
render() {
let coins = this.state.data.map(coin => (
// i am assuming you have and id field else change it to any unique value
<tr key={coin.id}>
<td>{coin.market_cap_rank}</td>
<td>{coin.symbol}</td>
<td>{coin.name}</td>
<td>{coin.market_cap}</td>
<td>{coin.current_price}</td>
<td>gerfds</td>
<td>@mdo</td>
</tr>
))
return (
<div className="container">
<HeadJumbotron />
<div className="container2">
<table striped bordered hover variant="dark">
<thead>
<tr>
<th>#</th>
<th>Sign</th>
<th>Name</th>
<th>Market Cap</th>
<th>Price</th>
<th>Change 24h</th>
<th>Buy</th>
</tr>
</thead>
<tbody>
{coins}
</tbody>
</table>
</div>
</div>
)
}
}
我只想补充一下阿尔坎塔拉的答案: super用于扩展React库中的道具
constructor(props) {
super(props);
this.state = {
data : [];
};
}
您经常会看到在JSX中执行的映射函数与最初的问题相同
render() {
return (
<div className="container">
<HeadJumbotron />
<div className="container2">
<table striped bordered hover variant="dark">
<thead>
<tr>
<th>#</th>
<th>Sign</th>
<th>Name</th>
<th>Market Cap</th>
<th>Price</th>
<th>Change 24h</th>
<th>Buy</th>
</tr>
</thead>
<tbody>
{this.state.data.map(coin => (
<tr key={coin.id}>
<td>{coin.market_cap_rank}</td>
<td>{coin.symbol}</td>
<td>{coin.name}</td>
<td>{coin.market_cap}</td>
<td>{coin.current_price}</td>
<td>gerfds</td>
<td>@mdo</td>
</tr>))}
</tbody>
</table>
</div>
</div>
)
}
对于您的特殊情况,我可能是错的,我看不出数据和样式都是什么,但显示内容列表的更传统的方式是使用标记