gpt4 book ai didi

javascript - react 处理事件

转载 作者:行者123 更新时间:2023-11-30 15:05:24 26 4
gpt4 key购买 nike

简单的待办事项列表。我想添加删除功能但出现错误:

proxyConsole.js:56 Warning: setState(...): Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount.

当我试图掌握它时,我可能会遇到绑定(bind)。

class App extends Component {
constructor(props) {
super(props);
this.onDelete = this.onDelete.bind(this);
this.state = {
todos: ['wash up', 'eat some cheese', 'take a nap'],
};
}

render() {
var todos = this.state.todos;
todos = todos.map(function(item, index){
return(
<TodoItem item={item} key={index} onDelete={this.onDelete}/>
)
}.bind(this));

return (
<div className="App">
<ul>
{todos}
</ul>
</div>
);
}

onDelete(item){
var updatedTodos = this.state.todos.filter(function(val, index){
return item !== val;
});
this.setState({
todos:updatedTodos
});
}
}

class TodoItem extends Component {
constructor(props) {
super(props);
this.handleDelete = this.handleDelete(this);

}

render(){
return(
<li>
<div className="todo-item">
<span className="item-name">{this.props.item}</span>
<span className="item-delete" onClick={this.handleDelete}> x</span>
</div>
</li>
);
}

handleDelete(){
this.props.onDelete(this.props.item);
}
}

最佳答案

I think you are invoking handleDelete handler in child component's constructor. It should be :

this.handleDelete = this.handleDelete.bind(this);

class App extends React.Component {
constructor(props) {
super(props);
this.onDelete = this.onDelete.bind(this);
this.state = {
todos: ["wash up", "eat some cheese", "take a nap"]
};
}

render() {
var todos = this.state.todos;
todos = todos.map(
function(item, index) {
return <TodoItem item={item} key={index} onDelete={this.onDelete} />;
}.bind(this)
);

return (
<div className="App">
<ul>
{todos}
</ul>
</div>
);
}

onDelete(item) {
var updatedTodos = this.state.todos.filter(function(val, index) {
return item !== val;
});
this.setState({
todos: updatedTodos
});
}
}

class TodoItem extends React.Component {
constructor(props) {
super(props);
this.handleDelete = this.handleDelete.bind(this);
}

render() {
return (
<li>
<div className="todo-item">
<span className="item-name">{this.props.item}</span>
<span className="item-delete" onClick={this.handleDelete}> x</span>
</div>
</li>
);
}

handleDelete() {
this.props.onDelete(this.props.item);
}
}

ReactDOM.render(<App />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"/>

关于javascript - react 处理事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45822454/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com