mongodb - 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;
解决方案
像这样初始化状态,删除posts
.
state = {
title: '',
typeOfProduction: ''
}
推荐阅读
- javascript - Express 不将箭头语法识别为前面带有导出的中间件(ES6)
- python - 将不规则长度元组列表转换为数据框
- java - 使用jdbc在mysql数据库中插入5000条记录需要太多时间
- javascript - 删除 jQuery 中的切片增量
- javascript - 我可以使用 discord.js 每秒获取多少条消息以防止 API 滥用?
- c# - 从工作 Task<> 交互(获取)变量值
- java - 按字母顺序显示 ArrayList
- arrays - Swift - 使用变量引用数组中的成员
- python - 从 PyQt5 窗口返回控制到脚本
- java - 使用 spring 过滤器在 Spring Boot 中记录原始 HTTP 请求和响应