【问题标题】:Trouble with handleSubmit for a form. (React/Mongoose/Nodejs)处理提交表单的问题。 (反应/猫鼬/Nodejs)
【发布时间】:2020-11-26 15:19:17
【问题描述】:

我正在用 React、Mongoose 和 Expressjs 做一个小项目,当我在表单上点击提交时,没有任何反应。我的快递服务器也出现此错误:

{ 说明: { ValidatorError: 路径 description 是必需的。

博客组件:

import React, { Component } from 'react'
import { Link } from '@reach/router'
import { getBlogs } from '../Api.jsx'
import AddBlog from '../components/AddBlog.jsx'


export default class Blog extends Component {
  state = {
    blogs: []
  }

  componentDidMount() {
    getBlogs()
      .then(res => {
          // console.log(res.data)
          this.setState({blogs: res.data})
      })
      .catch(err => {
          console.log(err)
      })
  }
  
  newPostedBlog = addedNewBlog => {
    this.setState(currentState => {
      return {
        blogs: [addedNewBlog, ...currentState.blogs]
      };
    });
  };
  
  render() {
      const {blogs} = this.state;
        return (
      <div className="blog-container">
        <Link to={`/blog/new`}>
        <button className="create-blog-button">Create new blog</button>
        </Link>
          <p className="blog-header">Blogs</p>
            <ul className="blog-ul">
             {blogs.map((blog) => (
               <li key={blog._id}>
                 <Link to={`/blog/${blog._id}`} className="link-to-single-blog">
                 <div className="blog-title">{new Date(blog.title).toLocaleDateString()}</div>
                 </Link>
                 <div className="blog-description">{blog.description}</div>
                 <div className="diary-btn-container">
                 <button className='diary-btn' onClick={this.handleClick}> Diary </button>
                 </div>
               </li>
            ))}
          </ul> 
      </div>
    )
  }
}

AddBlog 组件:

import React, { Component } from 'react';
import { postBlog } from '../Api.jsx';

export default class AddBlog extends Component {
  state = {
    description: ""
  }
  
  handleChange = event => {
    event.preventDefault()
    console.log(event.target.value)
    this.setState({ description: event.target.value})

  }
  
  handleSubmit = event => {
    event.preventDefault();
    const { description } = this.state;
    const { newPostedBlog } = this.props;
    postBlog(description).then(newBlog => {
      newPostedBlog(newBlog)
      this.setState({description: ""})
    })
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>
            <div className="description-box-container">
            <textarea onChange={this.handleChange}
                      placeholder="Say what's on your mind..." 
                      className="description-box"
                      rows="30"
                      cols="120"
                      type="text"
                      id="body"
                      value={this.state.description}>
            </textarea>
            </div>
            
          </label>
          <div className="submit-thoughts-btn-container">
          <button type='submit' className="submit-thoughts-btn"> Submit your thoughts! </button>
          </div>
        </form>
      </div>
    )    
  }
}

后端 POST 控制器:

exports.postBlog = (req, res) => {
    const newBlog = new Blog();
    newBlog.description = req.body.description;
    
    newBlog.save().then(newBlog => {
        res.send(newBlog)
    }).catch(err => {
        console.log(err)
    })
}

博客模型:

    const mongoose = require('mongoose')
    const Schema = mongoose.Schema;
    //npm package to force unique key as mongoose doesn't provide this
    const uniqueValidator = require('mongoose-unique-validator');
    
    // schema to define key types for blog schema
    const blogsSchema = new Schema({
        
        title: {
            
           type: Date,
           required: true,
           default: Date.now,
           unique: true
       
        },
        
        description: {
            
            type: String,
            required: true,
            unique: true
        }
})
    

Api.jsx:

export const postBlog = (id, title, description) => {
  const baseURL = 'https://f2f1c0aaf7de41d4bc57354de1d10938.vfs.cloud9.eu-west-1.amazonaws.com/blog/new'
  return axios.post(baseURL, { title, description}).then(res => {
    return res.data.blog;
  })
}

感谢任何帮助。对不起,如果我错过了什么,请告诉我。 :) 谢谢。

【问题讨论】:

  • 您能展示一下您的Blog 模型吗?
  • 如果你能在Api.jsx中显示你的postBlog函数
  • 请分享req.body 的样子。错误消息表明在Blog 模型架构中,description 字段是必需的,但是当您提交表单时,它不包含description 字段的值。
  • 你能把收到的值记录在你的postBlog in Api.jsx';
  • 我已经添加了博客和发布博客功能。现在看看其他 cmets :)

标签: node.js reactjs mongoose event-handling


【解决方案1】:

在您的提交函数中,您使用一个参数调用postBlog(description),但是在Api.jsxpostBlog 函数定义中,您收到3 个参数,这导致第二和第三参数未定义,因此description 未定义时你把它传递给你的帖子。

要解决此问题,您需要从函数定义中删除其他参数,或者在调用函数时传递它们。

请记住,根据您的 Blog 模型,title 也是必需的,并且在您当前的实现中,您还为 title 传递了 undefined。

【讨论】:

  • 啊,是的,我明白为什么它是未定义的,谢谢。对不起,我是大三学生,这是我的第一周。我还在学习!它给我的“newPostedBlog”不是一个函数。你能确认我正确地通过了道具吗?
  • 我没有看到您在Blog 组件中使用AddBlog 的位置,您在哪里显示AddBlog 组件?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
  • 2020-07-07
  • 2014-10-17
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
  • 2012-07-30
相关资源
最近更新 更多