![](/img/trans.png)
[英]Email Input Warning - A component is changing a controlled input of type text to be uncontrolled
[英]ReactJS - Warning: A component is changing an uncontrolled input of type text to be controlled
我試圖擺脫這個錯誤信息,但仍然沒有成功。
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>
);
}
}
在輸入中似乎總是一個非空值,我該如何解決這個問題?
在狀態項中定義為字符串,因此當您將值分配給文本輸入時,例如
<input type="text" value={this.state.items.item} className="form-control" onChange={this.handleChange}/>
你基本上是在寫
<input type="text" value={undefined} className="form-control" onChange={this.handleChange}/>
對於初始渲染,一旦 API 調用的結果可用並且項目狀態更改為包含項目鍵的對象,您將向輸入傳遞一個值,從而將其從不受控制的轉換為受控制的,這就是警告的內容。 為了避免警告,您只需像這樣初始化您的狀態
this.state = {items: { items: '' }};
或使用輸入
<input type="text" value={this.state.items.item || ''} className="form-control" onChange={this.handleChange}/>
當您嘗試將 undefined 值設置為任何輸入類型時,這種類型的警告主要發生在 React 中。 您可以使用條件運算符來檢查狀態值是否未定義,如果未定義,則將其設置為空值。
<input type="text" value={this.state.items.item !== undefined ? this.state.items.item : ''} className="form-control" onChange={this.handleChange}/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.