我正在尝试从对象在页面上显示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

最佳答案

您能够成功收到您的请求吗?

因为通过查看您的代码。它只会显示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

关于javascript - 我正在尝试从React中的对象(API)提取数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48292899/

10-11 08:24