reactjs - 使用 React 显示来自 fetch api 的数据

标签 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 个组件,即表,其中还有一个行组件。 我想在 Row 组件中显示变量 看起来像这样

<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 方法中将其作为 props 传递给 Table 组件:

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

然后从 Table 组件将其作为 props 传递给 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>
   ) 
}

关于reactjs - 使用 React 显示来自 fetch api 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44710304/

相关文章:

javascript - 在componentDidCatch之后重定向用户的方法

Photoshop jsx 将 activeDocument 设置为当前打开的文档

javascript - React App - 我的警告窗口出现两次

reactjs - Material UI - 概述的 TextField 不呈现轮廓

javascript - 如何显示图像的非常具体的部分

javascript - RxJS 和 React 的 setState - 延迟函数执行直到订阅

javascript - 理解 React 高阶组件

reactjs - 修复了 Material-UI@next (v1.0.0-beta.8) 中的表格标题和高度

javascript - 使用 .map 在 React 中使用 double for 循环

javascript - react ;无法读取 render > return() 内未定义的属性