【问题标题】:Response not rendering from axios get request in react响应未从 axios 呈现响应获取请求
【发布时间】:2019-11-03 19:22:56
【问题描述】:

我有以下代码

import React, { Component } from "react";
import { Link } from "react-router-dom";
import swal from "sweetalert";
import axios from "axios";

class Journal extends Component {
  constructor() {
    super();
    this.state = {
      journal: {
        title: "",
        content: "",
        createdAt: ""
      }
    };
  }

  componentDidMount() {
    let postId = this.props.match.params.id;
    axios
      .get("/api/journals/" + postId)
      .then(journal => this.setState({ journal }))
      .catch(error => {
        console.log(error);
      });
  }

  delete(id) {
    let postId = this.props.match.params.id;
    swal({
      title: "Are you sure?",
      text: "Once deleted, you will not be able to recover this journal!",
      icon: "warning",
      buttons: true,
      dangerMode: true
    }).then(willDelete => {
      if (willDelete) {
        axios.delete("/api/journals/" + postId).then(result => {
          this.props.history.push("/journals");
        });
        swal("Poof! Your journal has been deleted!", {
          icon: "success"
        });
      } else {
        swal("Your journal is safe!");
      }
    });
  }

  render() {
    return (
      <>
        <div className='p-12 text-gray-800'>
          <section className='max-w-3xl m-auto'>
            <article>
              <div className='text-center'>
                <h1 className='title'>{this.state.journal.title}</h1>

                <span className='text-sm'>{this.state.journal.createdAt}</span>
              </div>

              <div className='text-sm mt-10 mb-4'>
                {this.state.journal.content}
              </div>
            </article>

            <div className='mt-8 mx-auto text-center w-full'>
              <hr />
              <div className='my-4'>
                <Link
                  to={`/dashboard/journals/${this.props.match.params.id}/edit`}
                  className='btn btn-edit'
                >
                  Edit
                </Link>
                <span className='text-gray-200 mx-4'>|</span>
                <button
                  onClick={this.delete.bind(this)}
                  className='w-20 btn btn-delete'
                >
                  Delete
                </button>
              </div>
              <hr />
            </div>
          </section>
        </div>
      </>
    );
  }
}

export default Journal;

使用 fetch 所有来自 setState 的数据被渲染,即

fetch("/api/journals/" + postId)
 .then(res => res.json())
 .then(journal => this.setState({ journal }))
 .catch(error => {
   console.log(error);
});

这行得通。

但是,当我返回 JSON 响应时,Axios 似乎是更好的选择。另外,我希望更多地使用它。

但据我所知,我正在使用 axios 正确设置状态,我收到 200 响应,但数据未显示。

【问题讨论】:

  • axios 为您的数据添加一个包装器,您的日志可能是response.data,您可以通过记录 axios 返回的值来找到这一点
  • 如果我这样做.then(response =&gt; console.log(response.data)),我会得到一系列我的期刊,那么我该如何设置状态?
  • 你试过把这个:.then(journal =&gt; this.setState({ journal }))改成这个:.then(res =&gt; this.setState({ journal: res.data }))
  • 我收到TypeError: "result is undefined"
  • 数据仍在控制台记录中

标签: javascript reactjs axios


【解决方案1】:

试试这个:

axios.get(`/api/journals/${postId}`)
.then((res) => {
    this.setState({journal: res.data})
})
.catch((err) => {
    console.log(err);
})

【讨论】:

    【解决方案2】:

    假设您在响应正文中以 json 形式获得 single 日记。

    如果你这样写

    axios
      .get("/api/journals/" + postId)
      .then(journal => this.setState(journal.data))
      .catch(error => {
        console.log(error);
    });
    

    journal 是这里的响应,所以您可以通过 journal.data 访问数据。

    由于这里的response是一个对象,data是属性,所以可以直接访问{ data }这样的数据。所以你也可以写。

      axios
        .get("/api/journals/" + postId)
        .then(({ data }) => this.setState({ data }))
        .catch(error => {
        console.log(error);
      });
    

    如果您的响应是数组,那么您可以通过response.data 获取其值。

    希望这会有所帮助。如果您有其他要添加的内容,您可以改进它。

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 2020-09-01
      • 2017-03-28
      相关资源
      最近更新 更多