【问题标题】:How to get data from json using axios in react?如何在反应中使用 axios 从 json 获取数据?
【发布时间】:2019-07-14 12:19:40
【问题描述】:

有两个文件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>

错误: 实际上,我想在 react 中使用 ajax 将 reactjs.json 文件中的数据提取到 index.html 中。我为此使用 axios,而我使用 cdn 进行反应。但我无法获取数据。

我试图将它放在 FetchDem 类的 componentDidMount() 中,但不起作用,所以我将它传递给了构造函数,但我仍然无法访问数据。

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

【问题讨论】:

  • 将响应 imagesLink 分配给 state
  • 你是说this.setState{imageslink:res.data};

标签: json ajax reactjs axios


【解决方案1】:

React 文档建议使用 componentDidMount 进行 API 调用。

此外,当您获取数据时,您必须将其保持在状态中。稍后数据将在 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>

【讨论】:

  • 你能为这个@jordanenev 提供jsfiddle吗
  • 这是一篇关于使用Axios in React 的好文章。它遵循与我的答案相同的想法。
  • @AyushSrivastava 我添加了一个有效的 Axios 示例,我在其中调用公共 JSON API(使用假用户)并列出响应。我相信您可以根据自己的需要进行调整。干杯! :)
猜你喜欢
  • 2020-06-28
  • 2019-08-09
  • 2018-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-23
  • 2017-05-11
  • 2021-11-02
相关资源
最近更新 更多