0
import React, {useState, useEffect} from 'react'

import { NoMoralisContextProviderError } from 'react-moralis';

import './css/createpost.css'

import { useMoralis } from "react-moralis";

function CreatePost() {

    const [title, setTitle] = useState("")

    const [content, setContent] = useState("")

    const { Moralis, isInitialized } = useMoralis();

    const createNewPost = (e, title, content) => {

        e.preventDefault()

        const newPost = Moralis.Object.extend("Posts");

        const post = new newPost();

        post.set("title", title);

        post.set("content", content);

        post.save();

        return post;

    }

    return (

        <div>

            <div>

            <form action="#" className="createpost">

               <div class="data">

                  <label>Title</label>

                  <input type="text" required onChange={(e) => setTitle(e.target.value)}/>

               </div>

               <div class="data">

                  <label>Content</label>

                  <input type="text" required onChange={(e) => setContent(e.target.value)}/>

               </div>

               <div class="btn">

                  <div class="inner"></div>

                  <button type="submit" onClick={createNewPost(e, title, content)}>Submit Post</button>

               </div>

            </form>

            </div>

      </div>

    )

}

export default CreatePost

我正在尝试将数据保存到数据库中,但是在每次输入更改后都会保存它。因此,如果我输入“hello”,它会保存“h”、“he”、“hel”、“hell”、“hello”,我希望它只保存一次 hello。不是每个输入都改变。有人可以帮我解决这个问题吗?

我正在尝试将其保存到moralis 数据库,但我认为错误是该函数被多次调用。

4

1 回答 1

0

将处理程序包装到箭头函数

 <button type="submit" onClick={() => createNewPost(e, title, content)}>Submit Post</button>
于 2021-11-15T15:06:32.677 回答