【发布时间】: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 => console.log(response.data)),我会得到一系列我的期刊,那么我该如何设置状态? -
你试过把这个:
.then(journal => this.setState({ journal }))改成这个:.then(res => this.setState({ journal: res.data })) -
我收到
TypeError: "result is undefined" -
数据仍在控制台记录中
标签: javascript reactjs axios