首页 > 解决方案 > 为什么我在修补数据时返回 null

问题描述

我正在修补我的数据,但是当我这样做时,我的数据最终的值为null. 我什console.log至发送到我的数据库的值并且我得到了正确的值,但由于某种原因在我的数据库中它显示为空。

,    "going":null, "date":"2020-11-10T17:34:11.135Z", "__v":0},
ivs","going":2,    "date":"2020-11-11T04:19:24.433Z", "__v":0}]

正如你所看到的,“going”应该有一个整数作为它的值,而不是我修补的那个显示null

对于如何解决这个问题,有任何的建议吗?

import React from "react";
import "./App.css";
import axios from "axios";

export default class Scroll extends React.Component {
    state = {
        posts: [],
        id: 0,
    };

    componentDidMount() {
        axios.get("http://localhost:5000/posts/save").then((res) => {
            const posts = res.data;
            this.setState({ posts });
        });
    }

    handleClick = (id) => {
        var i;
        for (i = 0; i < this.state.posts.length; i++) {
            if (this.state.posts[i]._id === id) {
                let x = this.state.posts[i].going + 1;
                axios({
                    url: `http://localhost:5000/posts/save/${id}`,
                    method: "PATCH",
                    data: x,
                })
                    .then(() => {
                        console.log(x);
                    })
                    .catch(() => {
                        console.log("Internal server error");
                    });
            }
        }
    };

    render() {
        return (
            <div className="flex-container">
                {this.state.posts.reverse().map((posts) => (
                    <div className="post">
                        <h3 id="post-text">{posts.title}</h3>
                        <p id="post-text">{posts.body}</p>
                        <p>{posts.going}</p>
                        <button onClick={() => this.handleClick(posts._id)}>Going</button>
                    </div>
                ))}
            </div>
        );
    }
}

标签: javascriptreactjsmongodbexpressaxios

解决方案


推荐阅读