使用react显示来自fetch api的数据

时间:2017-06-22 22:30:17

标签: reactjs jsx

我正在开发一个简单的网站,它使用react来显示来自API(JSON)的数据到页面中。

我正在使用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个组件,Table,它也有一个行组件。 我想在Row组件中显示变量 看起来像这样

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

2 个答案:

答案 0 :(得分:2)

你是构造函数:

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组件中将其作为道具传递给Row组件,因此:

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 }, ..... ]
}

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

因此,您的Table组件应如下所示:

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

答案 1 :(得分:0)

如果你在componentDidMount中进行ajax调用,那么当状态发生变化时,React会重新发送(https://facebook.github.io/react/docs/react-component.html#componentdidmount)。但是,在请求结算和React重新呈现之前,您仍然需要预测volumeticker道具将为空。

相关问题