use*_*090 6 javascript reactjs
我试图摆脱这个错误消息,但仍然没有成功.
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.
Run Code Online (Sandbox Code Playgroud)
还有链接到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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
在输入似乎总是一个非空值,我该如何解决这个问题?
Shu*_*tri 16
在状态项中定义为字符串,因此当您将值分配给文本输入时
<input type="text" value={this.state.items.item} className="form-control" onChange={this.handleChange}/>
Run Code Online (Sandbox Code Playgroud)
你本质上是写作
<input type="text" value={undefined} className="form-control" onChange={this.handleChange}/>
Run Code Online (Sandbox Code Playgroud)
对于初始渲染,一旦API调用的结果可用并且项目状态更改为包含项目键的对象,您将一个值传递给输入,从而将其从不受控制转换为受控,这就是警告的内容.为了避免警告,你只需要初始化你的状态
this.state = {items: { items: '' }};
Run Code Online (Sandbox Code Playgroud)
或使用输入
<input type="text" value={this.state.items.item || ''} className="form-control" onChange={this.handleChange}/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6883 次 |
| 最近记录: |