如何解决我正在从我的 nodejs 中获取动态数据到 reactjs,但我收到一条错误消息,提示“POST 未定义”
我已经使用 node 在我的 mongodb 数据库中创建了条目,现在我正在尝试从后端获取该数据以响应前端,用于 node 中跨平台的第 3 方应用程序是 cors,而 react 是 axios(在脚本中我添加了 "proxy":"http://localhost:5000"(5000 是我的后端端口)
这是我的 NovelCard.js 代码
import React,{ Component } from 'react';
import { Container } from 'react-bootstrap';
import Card from 'react-bootstrap/Card';
import axios from 'axios';
const createSet = (post) => {
<Card style={{ width: '18rem' }}>
<Card.Img variant="top" src="holder.js/100px180" />
<Card.Body>
<Card.Title>{post.name}</Card.Title>
<Card.Subtitle className="mb-2 text-muted">{post.author}</Card.Subtitle>
<Card.Text>{post.synopsis}</Card.Text>
</Card.Body>
</Card>;
};
class Latest extends Component {
state = {
name: '',author: '',synopsis: '',post: [],};
componentDidMount = () => {
this.getData();
};
getData = () => {
axios
.get('http://localhost:5000/novels/')
.then((res) => {
const data = res.data;
this.setState({ post: data });
console.log('data recived');
})
.catch(() => {
alert('error');
});
};
render() {
console.log('state',this.state);
return <Container>{post.map(createSet)}</Container>;
}
}
export default Latest;
我收到错误提示 ***
src\components\home\Latest\NovelCard.js Line 45:24: 'post' 不是 已定义无未定义
解决方法
您的 post
变量在您所在的州内可用。您需要在 render
函数中执行类似操作。
render() {
console.log('state',this.state);
return <Container>{this.state.post.map(createSet)}</Container>;
}
或者你也可以这样做。
render() {
const { post } = this.state;
console.log('state',this.state);
return <Container>{post.map(createSet)}</Container>;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。