【发布时间】:2018-01-17 02:54:41
【问题描述】:
我正在尝试从一个对象在页面上显示 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
【问题讨论】:
-
等待组件挂载,然后调用将设置状态并触发重新渲染的api。也就是说,将这些 api 调用移动到 componentDidMount 而不是 willMount
标签: javascript reactjs api