首页 > 解决方案 > 我正在从我的 nodejs 获取动态数据到 reactjs,但我收到一条错误消息“POST 未定义”

问题描述

我已经使用节点在我的 mongodb 数据库中创建了条目,现在我正在尝试从后端获取该数据以响应前端用于节点中跨平台的第 3 方应用程序是 cors,而反应是 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' is not defined no-undef


标签: node.jsreactjsmongodbmern

解决方案


您的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>;
}

推荐阅读