首页 > 解决方案 > React POST 请求输入值错误

问题描述

所以我正在尝试添加一个 NewPost 并且我得到了:

“警告:组件正在更改要控制的文本类型的不受控输入。输入元素不应从不受控切换到受控(反之亦然)。决定在组件的生命周期内使用受控输入元素还是不受控输入元素。”

...当它说“this.state.title”时出错

Ps:我正在使用nodejs,mongodb和react

e.preventDefault();

  const newPost = {

  title: this.state.title,
  typeOfProduction: this.state.typeOfProduction
  };

这是我的代码:

 import React, { Component } from 'react';
 import './NewPost.css';


 class NewPost extends Component {
state = {
    posts:{
        title: '',
        typeOfProduction: ''
    }   
}

postDataHandler(e) {
    e.preventDefault();
    const newPost = {
      title: this.state.title,
      typeOfProduction: this.state.typeOfProduction
    };
    fetch('/projects', {
      method: 'POST',
      body: JSON.stringify(newPost),
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(console.log);

}
render(){

return(
        <div className="Dashboard container-fluid">
        <div className="NewPost">
            <h1>Add a Post</h1>
            <label>Title</label>
            <input type="text" value={this.state.title} name="title" ref="title" onChange={(event) => this.setState({title: event.target.value})} />
            <label>Type of Production</label>
            <select value={this.state.typeOfProduction} name="typeOfProduction" ref="typeOfProduction" onChange={(event) => this.setState({typeOfProduction: event.target.value})}>
                <option value="Fiction">Fiction</option>
                <option value="Tv">TV</option>
                <option value="Tv">Documentary</option>
            </select>

            <button type="submit" onClick={this.postDataHandler}>Add Post</button>
        </div>
    </div>
 );
}
}


export default NewPost;

标签: mongodbreactjspostinputfetch

解决方案


像这样初始化状态,删除posts.

state = {
     title: '',
    typeOfProduction: ''
}

推荐阅读