我试图在对象上显示页面上的API数据。
我试图在camperlist.js文件中显示CamperList变量中的数据,但是我遇到了麻烦。
我将粘贴我用于检索API的每个文件的代码。
以下是camperlist.js文件中的代码:
import React from 'react';
import CamperListItem from './camper_list_item.js'
//This is where the data is being pulled from VVVV
const CamperList = (props) => {
console.log('these are the datas', props.campers);
return (
<div> hello world </div>
);
}
export default CamperList
在下一个文件中,您将找到正在呈现的“CamperList”组件。
这是App.js文件:
import React, { Component } from 'react';
import logo from './logo.svg';
//import './App.css';
import axios from 'axios';
import CamperList from './camperlist'
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
recentCampers: [],
allTimeCampers: [],
currentView: 'recentCampers'
}
}
componentWillMount() {
let current = this;
axios.all([this.fetchRecent(), this.fetchAllTime()]).then(axios.spread(function(recentCampers, allTimeCampers){
current.setState({ recentCampers, allTimeCampers});
}));
}
fetchRecent(){
return axios.get('https://fcctop100.herokuapp.com/api/fccusers/top/recent')
}
fetchAllTime(){
return axios.get('https://fcctop100.herokuapp.com/api/fccusers/top/alltime')
}
changeView(currentView){
this.setState({currentView})
}
render() {
return (
<div>
<h2> viewing top {this.state.currentView} </h2>
<button onClick={()=> this.changeView('recentCampers')} className="btn btn-primary"> Recent </button>
<button onClick={() => this.changeView('allTimeCampers')} className="btn btn-primary"> All Time </button>
<CamperList campers={this.state[this.state.currentView]}/>
</div>
);
}
}
这是camper_list_item.js文件:
import React from 'react';
const CamperListItem = (props) => {
return(
<div> camper item </div>
);
}
export default CamperListItem
答案 0 :(得分:0)
您是否能够成功收到您的请求?
因为看了你的代码。它只会显示hello world
。
您应该更改CamperList组件,以显示您的请求。
import React from 'react';
import CamperListItem from './camper_list_item.js'
//This is where the data is being pulled from VVVV
const CamperList = (props) => {
return (
<div>
{props.campers.map(c => {
return <div key={c.username}>{c.username}</div>
}}
</div>
);
}
export default CamperList
答案 1 :(得分:0)
在循环浏览CamperListItem
中的campers
道具后,您可以返回CamperList
组件。
import React from 'react';
import CamperListItem from './camper_list_item.js'
const CamperList = (props) => {
return (
<div>
{
props.campers.map((camper, i) => {
return <CamperListItem camper={camper} key={i} />
}
}
</div>
);
}
export default CamperList;
这里我举例说明了使用CamperListItem
赋予的道具的一个例子:
import React from 'react';
const CamperListItem = (props) => {
return(
<div>{props.camper.name}</div>
);
}
export default CamperListItem