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

我正在使用fetch()API。

我可以从API获取数据并将其设置为“ App”组件状态,但无法传递给手动创建的Table和Row组件。

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='' />

最佳答案

您的构造函数:

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>
   )
}

07-25 21:47
查看更多