如何使用axios渲染React 16中的文本数据

时间:2018-01-12 05:10:58

标签: javascript reactjs axios

我的最终目标是在React js中呈现API的文本数据。到目前为止我已经完成了整合axios来获取数据。我的挑战是因为我从URL获取的数据只是一个文本。我不能将数据解析或获取为JSON。我能够在浏览器网络选项卡下看到文本响应为文本。我无法在前视图中看到它。 如何在React中映射和呈现所有文本数据?

import React, { Component } from "react";
import { Grid, Row, Col } from "react-bootstrap";
import axios from "axios";
class About extends Component {
  constructor() {
    super();
    this.state = {
      posts: []
    };
  }

  componentDidMount() {
    axios
      .get(
        "http://cors-anywhere.herokuapp.com/http://terriblytinytales.com/test.txt"
      )
      .then(res => {
        const posts = res.data.map(obj => obj.data);
        this.setState({ posts });
      })
      .catch(error => {
        console.log((error));
      });
  }

  render() {
    return (
      <Grid>
        <Row>
          <Col xs={12} md={6}>
            <h1>fetched data</h1>
            <ul>
              {this.state.posts.map((post, id) => <li key={id}>{post}</li>)}
            </ul>
          </Col>
        </Row>
      </Grid>
    );
  }
}
export default About;     

1 个答案:

答案 0 :(得分:3)

class About extends React.Component {
  constructor() {
    super();
    this.state = {
      posts: []
    };
  }

  componentDidMount() {
    axios
      .get(
        "https://cors-anywhere.herokuapp.com/http://terriblytinytales.com/test.txt"
      )
      .then(res => {
        //console.log("res", res)
        const posts = res.data
        //debugger
        this.setState({ posts });
      })
      .catch(error => {
        console.log((error));
      });
  }

  render() {
  //console.log(this.state.posts)
    return (
      <div>
        <div>
          <div xs={12} md={6}>
            <h1>fetched data</h1>
            <ul dangerouslySetInnerHTML={{__html: this.state.posts}}>
            </ul>
          </div>
        </div>
      </div>
    );
  }
}
ReactDOM.render(<About />, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-bootstrap/0.32.0/react-bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.js"></script>
<div id="root"></div>

希望这有帮助