![](/img/trans.png)
[英]what `?` means before some object attribute? and why my ts file doesn´t accept it?
[英]Why my setState doesn't accept this object?
我在 React 的待辦事項列表中工作,當調用方法deleteItem
時,我得到Uncaught Error: Objects are not valid as a React child (found: object with keys {text})
但我不明白原因
class Form extends Component{
constructor(props){
super(props);
this.state = {
task: "",
list: []
}
this.saveItem = this.saveItem.bind(this);
this.deleteItem = this.deleteItem.bind(this);
}
saveItem(event){
let state = this.state;
event.preventDefault();
if(this._taskInput.value !== ""){
state.list.push({ text: this._taskInput.value });
this.setState(state);
}
this.setState({task: ""});
}
deleteItem(index){
const {list} = this.state;
this.setState({
list: list.filter((item,itemCurrent) => {
// console.log(item.key, index);
return (itemCurrent !== index);
}),
});
}
render(){
return(
<Fragment>
<form onSubmit={this.saveItem}>
<input value= {this.state.task} id="to-do"
onChange={(e) => this.setState({task: e.target.value})}
ref={event => this._taskInput = event} type="text" className="validate"/>
<label htmlFor="to-do">My tasks</label>
</div>
<button type="submit" name="action">Submit
</button>
</div>
{{this.state.task}}
{this.state.list}
</form>
</div>
<Table list= {this.state.list} deleteItem = {this.deleteItem}/>
問題是渲染中的這一行: {this.state.list}
。 您可以渲染數組,但不能渲染 object。 解決的辦法是map過陣列和output下面的一些JSX。 假設您有一個具有name
和id
屬性的對象列表:
{this.state.list.map(item => (<div key={item.id}>{item.id}</div>))}
首先這里有一個很大的概念錯誤:
if (this._tarefaInput.value !== ""){
state.list.push({ text: this._taskInput.value });
this.setState(state);
}
您正在直接編輯 state 與該推 function,您不應該在反應中這樣做,因為它會導致意想不到的后果,這就是您應該如何更新 state:
if (this._tarefaInput.value !== ""){
//use the spread operator (...) to create a copy of the list in the state
const newList = [... state.list];
// push the new element tot the new list
newList.push({ text: this._taskInput.value });
// update the state
this.setState({list: newList});
}
現在你得到的錯誤很可能發生,因為在你的代碼中的某個地方(可能在<Table/>
內)你試圖將列表數組的每個元素打印為一個反應組件。 您尚未共享列表呈現的部分,但我猜您正在做這樣的事情:
//somewhere inside a render:
{
list.map(Element => <Element />);
}
//Proper way of doing it
{
list.map(element => <p>{element.text}</p>);
}
如果您共享更多代碼和帶有錯誤描述的整個日志(帶有文件和行號),我可以嘗試提供更多幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.