【发布时间】:2018-07-18 16:29:12
【问题描述】:
我正在尝试摆脱此错误消息,但仍然没有成功。
Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
还有指向 Facebook 页面的链接,但我仍然不知道如何弄清楚。
class EditItem extends Component {
constructor(props) {
super(props);
this.state = {items: ''};
this.addItemService = new ItemService();
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount(){
axios.get('http://localhost:3005/items/edit/'+this.props.match.params.id)
.then(response => {
this.setState({ items: response.data });
})
.catch(function (error) {
console.log(error);
})
}
handleChange = (e) => {
let items = Object.assign({}, this.state.items); //creating copy of object
items.item = e.target.value; //updating value
this.setState({items});
}
handleSubmit(event) {
event.preventDefault(); // not sure why this
this.addItemService.updateData(this.state.items.item, this.props.match.params.id); // service for updating the data
this.props.history.push('/index'); // redirect
}
render() {
return (
<div className="container">
<form onSubmit={this.handleSubmit}>
<label>
Edit Item:
<input type="text" value={this.state.items.item} className="form-control" onChange={this.handleChange}/>
</label><br/>
<input type="submit" value="Update" className="btn btn-primary"/>
</form>
</div>
);
}
}
在输入中似乎总是一个非空值,我该如何解决这个问题?
【问题讨论】:
-
this.state.items.item是undefined,直到第一个onChange事件。您可以将初始状态更改为this.state = {items: { item: '' } };以消除警告。
标签: javascript reactjs