【发布时间】:2019-07-06 13:27:52
【问题描述】:
我目前正在构建一个带有 .net 核心后端的反应应用程序。我当前的问题在于用于编辑文章的视图(仅由标题和描述组成)。在componentDidMount 上,我从路由中获取路由参数 id 并使用它从服务器检索文章(我已经验证它可以正常工作)。我的问题是我的表单没有填写获取的数据。我的理解是,由于表单字段设置为this.state...,那么它们应该随着状态更新而更新,但这不是我所看到的。我认为问题可能在于我在控制台中收到的警告:
index.js:2177 警告:组件正在更改受控输入 类型隐藏不受控制。输入元素不应从 受控到不受控(反之亦然)。决定使用 受控或不受控的输入元件的寿命 组件。
我已阅读警告指向的文档,但没有看到我的组件如何违反此规定。
我的组件如下:
import React, { Component } from 'react';
import CKEditor from 'react-ckeditor-component';
export class ArticlesEdit extends Component {
displayName = ArticlesEdit.name
constructor(props) {
super(props);
this.state = {
title: '',
description: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount () {
const { id } = this.props.match.params;
fetch(`https://localhost:44360/api/articles/${id}`)
.then((article) => {
this.setState({
title: article.title,
description: article.description
});
});
}
updateDescription(event){
this.setState({description: event.target.value});
}
render() {
return(
<form onSubmit={this.handleSubmit} >
<div className="form-group row" >
<label className=" control-label col-md-12" htmlFor="Title">Title</label>
<div className="col-md-4">
<input className="form-control" type="text" id="title" name="title" defaultValue={this.state.title} required />
</div>
</div >
<CKEditor activeClass="editor" content={this.state.description} events= {{"change": this.onEditorChange.bind(this) }} />
<input type="hidden" id="description" name="description" value={this.state.description} onChange={this.updateDescription}/>
<div className="form-group">
<button type="submit" className="btn btn-default">Save</button>
</div >
</form >
);
}
onEditorChange(evt){
var newContent = evt.editor.getData();
this.setState({
description: newContent
});
}
handleSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
console.log(this.state.title);
// POST request for Add employee.
fetch('https://localhost:44360/api/articles/', {
method: 'PUT',
body: data
}).then((response) => response.json())
.then((responseJson) => {
this.props.history.push("/articles");
})
}
}
【问题讨论】:
标签: reactjs