如何在React中使用axios从json获取数据?

时间:2019-02-20 18:01:42

标签: json ajax reactjs axios

其中有两个文件reactjs.json。

{
    "642176ece1e7445e99244cec26f4de1f": 
    ["https://ih1.redbubble.net/image.487729686.1469/pp,550x550.jpg", 
    "https://ik.imagekit.io/PrintOctopus/s/files/1/0006/0158/7777/products/abey_pagal_hai_kya.png?v=1547744758"]
}

和index.html

<!DOCTYPE html>
<html>

<head>
  <title>Image Viewer-Static</title>
  <!-- <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css"
    />
    <link
      rel="stylesheet"
      href="https://use.fontawesome.com/releases/v5.7.2/css/all.css"
    />
    <link
      rel="stylesheet prefetch"
      href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css"
    />
    <link rel="stylesheet" href="style.css" /> -->
</head>

<body>
  <div id="root"></div>

  <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

  <script type="text/babel">

    var imageslink;
class FetchDemo extends React.Component {
        constructor(props) {
          super(props);
        }


        render() {
          return (
            <div>
                <Pictures apikeys="642176ece1e7445e99244cec26f4de1f" />
            </div>
          );
        }

      }

      class Pictures extends React.Component {

      constructor(props) {
          super(props);
         axios.get('reactjs.json').then(
          res => {
            console.log(res.data);
             imageslink = res.data;
            console.log(imageslink);
        })
      }

        render() {

          return (
          <div>
              {imageslink[this.props.apikeys].map(function(name, index){
                    return <img key={index} src={name} />;
                  })}
          </div>

           );
        }
      }

      ReactDOM.render(
        <FetchDemo/>,
        document.getElementById("root")
      );
    </script>
</body>

</html>

错误: error 实际上,我想在React中使用Ajax将数据从reactjs.json文件提取到index.html中。我为此使用axios,并且为了响应,我使用cdn。但是我无法获取数据。

我试图将其放在FetchDem类的componentDidMount()中,但无法正常工作,因此我将其传递到了构造函数中,但仍然无法访问数据。

所以我的问题是如何将数据从reactjs.json文件访问到index.html?

1 个答案:

答案 0 :(得分:1)

反应文档建议对API调用使用componentDidMount

此外,在获取数据时,还必须保持其状态。稍后,数据将在render方法中可用。

这是您必须调整代码的方式

constructor(props) {
    super(props);

    this.state = {  imageslink: null }
 }

componentDidMount() {
    axios.get('reactjs.json').then( res => {
      this.setState({ imageslink: res.data })
    })
}

render() {
  const { imageslink } = this.state

  if (imageslink) {
  // Here you can access this.state.imageslink,
  // because they will be fetched.
  }
}

这是一个通用的Axios React示例:

class App extends React.Component {
  constructor(props) {
    super(props)
    
    this.state = { users: [] }
  }
  
  componentDidMount() {
    axios.get('https://reqres.in/api/users?page=1')
      .then(response => this.setState({ users: response.data.data }))
  }
  
  renderUsers() {
    const { users } = this.state
    
    return users.map( user => (
      <div key={user.id}>{user.first_name} {user.last_name}</div>
    ))
  }
  
  render() {
    return <div>{ this.renderUsers() }</div>
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('container')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>

相关问题
最新问题