所以我试图添加一个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;
答案 0 :(得分:2)
像这样初始化状态,删除posts
。
state = {
title: '',
typeOfProduction: ''
}