我無法發現代碼有什麼問題。我通過道具傳遞狀態,newItem確實通過了,但我沒有更新Todos
組件的狀態。未能添加項目和更新狀態是react.js
class AddTodo extends React.Component {
constructor(){
super();
this.state = {text: ''};
}
onTextChanged(e){
this.setState({text:e.target.value});
}
addHandler(){
this.props.addTodo(this.state.text);
}
render() {
return(
<div>
<input type="text" onChange={(e)=>this.onTextChanged(e)} />
<button onClick={()=>this.addHandler()}>Add</button>
</div>
)
}
}
class Todos extends React.Component {
constructor(){
super();
this.state = {data: ['write book','wash clothes','jogging']};
}
addTodo(item){
const newData = [...this.state.data, item]; //problem is here
this.setState({ data: newData }); //problem is here
console.log(this.state.data)
}
render() {
return (
<div>
<AddTodo addTodo={(item)=>this.addTodo(item)}/>
<ul>
{this.state.data.map((item)=><TodoItems key={item} item={item}/>)}
</ul>
</div>
);
}
}
http://jsbin.com/nitibinale/1/edit?html,js,console,output
你如何將'AddTodo'函數綁定到實例?我看到匿名函數,但是'this'將會是錯誤的值。控制檯中的任何東西?您採取了哪些步驟進行調試? –
@DaveNewton爲什麼我需要綁定? es6的箭頭功能不在這裏完成任務嗎? –
@DaveNewton http://jsbin.com/pajoliboqi/1/edit不工作,如果我不使用es6 –