2017-06-22 101 views
1

我正在开发一个简单的网站,使用反应将数据从API(JSON)显示到页面中。使用反应显示来自提取API的数据

我正在使用fetch()API。

我能够从API获取数据并将其设置为“应用”组件状态,但我无法传递到我手动创建的表格和行组件。

class App extends React.Component { 
    constructor (props) { 
    super(props) 
    this.state = {ticker: {}, volume: {}} 
    this.loadData = this.loadData.bind(this) 
    this.loadData() 
    } 

    loadData() { 
    fetch(ticker) 
      .then((resp) => resp.json()) 
      .then((data) => { 

      this.setState({ 
       ticker: data 
      }) 
      }) 
      .catch((err) => { 
      console.log(err) 
      }) 
    fetch(volume) 
      .then((resp) => resp.json()) 
      .then((data) => { 

      this.setState({ 
       volume: data 
      }) 
      }) 
      .catch((err) => { 
       console.log(err) 
      }) 
    } 


    render() { 
    return (
     <div> 
     <Navbar /> 
     <div className='container'> 
      <div className='align'> 
      <div className='element' /> 

      </div> 
      <Table volume={this.state.volume} ticker={this.state.ticker} /> 

     </div> 
     </div> 

    ) 
    } 
} 

底线: 我有数据的API,并且我有3个部件,表,其中也有一排组件。 我想在行组件 它看起来像这样

<Row img='eth' name='Ethereum' price='' volume='' change='' marketCap='' /> 

回答

0

您的构造函数:

constructor (props) { 
    super(props); 
    this.state = {ticker: {}, volume: {}} 
    this.loadData = this.loadData.bind(this); 
    } 

为了获取你需要经常使用生命周期的组件,如componentDidMountcomponentWillMount数据,即:

componentDidMount(){ 
    this.loadData() 
} 

然后在你的国家,你将有数据。

在你render方法把它作为道具的Table组件:

render(){ 
    return(
     <Table volume={this.state.volume} ticker={this.state.ticker} /> 
    ) 
} 

然后从Table组件传递给组件作为道具,这样的:

render(){ 
    return(
    <Row img='eth' name='Ethereum' price='' volume={this.props.volume} change='' marketCap='' /> 
    ) 
} 

如果你有物体阵列,如:

this.state = { 
    volume: [ {name: "One", size: 1 }, {name: "Two", size: 2 }, ..... ] 
} 

您需要遍历数组并显示每个对象的组件。

因此,您Table成分应该是如下:

render(){ 
    return (
     <div>{this.props.volume.map(vol => <Row img='eth' name='Ethereum' price='' volume={vol} change='' marketCap='' />) }</div> 
    ) 
} 
+1

谢谢!我们现在将数据操作成一个数组,以便映射它们。 – Satonamo

0

如果使Ajax调用在componentDidMount显示变量,随即反应过来就会重新呈现在状态改变时(https://facebook.github.io/react/docs/react-component.html#componentdidmount)。但是,您仍然必须预计volumeticker道具将为空,直到请求解析并且React重新提交。

+0

呀,那究竟发生了什么,我猜。一旦提取完成,我该如何渲染数据? – Satonamo

+0

从'componentDidMount'调用'loadData'。 React将会在状态改变时重新投入。 –

+0

好的,谢谢。我刚刚做到了。 – Satonamo

相关问题