Javascript 在ReactJS项目中触发两次onChange事件
有人能解释一下为什么这个事件会被触发两次吗 这是我的主要内容组件Javascript 在ReactJS项目中触发两次onChange事件,javascript,reactjs,events,event-handling,Javascript,Reactjs,Events,Event Handling,有人能解释一下为什么这个事件会被触发两次吗 这是我的主要内容组件 class MainContent extends React.Component { constructor() { super() this.state = { todos: ToDosData } this.handleChange = this.handleChange.bind(this) } handleChange(id) { this.setState(pr
class MainContent extends React.Component {
constructor() {
super()
this.state = {
todos: ToDosData
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(id) {
this.setState(prevState => {
const updatedToDos = prevState.todos.map(todo => {
if (todo.id === id) {
console.log(!todo.completed)
todo.completed = !todo.completed
}
return todo
})
console.log(updatedToDos)
return {
todos: updatedToDos
}
})
}
render() {
const mainBodyStyles = {
color: "#FF8C00",
backgroundColor: "#fG7B02",
}
const todoItems = this.state.todos.map(item =>
<TodoItem
key={item.id}
item={item}
handleChange={this.handleChange}
/>)
return (
<div style={mainBodyStyles}>
{todoItems}
</div>
)
}
class MainContent扩展了React.Component{
构造函数(){
超级()
此.state={
todos:ToDosData
}
this.handleChange=this.handleChange.bind(this)
}
手柄更换(id){
this.setState(prevState=>{
const updatedToDos=prevState.todos.map(todo=>{
if(todo.id==id){
console.log(!todo.completed)
todo.completed=!todo.completed
}
返回待办事项
})
console.log(updatedoos)
返回{
待办事项:更新的待办事项
}
})
}
render(){
常量主体样式={
颜色:“FF8C00”,
背景色:“fG7B02”,
}
const todoItems=this.state.todos.map(项=>
)
返回(
{todoItems}
)
}
这是我的待办事项组件
function TodoItem(props) {
return (
<div>
<input
type="checkbox"
checked={props.item.completed}
onChange={() => props.handleChange(props.item.id)}
/>
<p>{props.item.text}</p>
</div>
)
功能待办事项(道具){
返回(
props.handleChange(props.item.id)}
/>
{props.item.text}
)
}
当我点击复选框时,它会运行事件函数两次。我不知道我做错了什么。提前谢谢 我认为,之所以会发生这种情况,是因为App.js handleChange函数中的this.setState调用正在改变prevState的状态
handleChange(id){
this.setState((prevState)=>{
让updatedToDos=prevState.todos.map(
todo=>{
让tempItem=Object.assign({},todo);
if(tempItem.id==id){
console.log(“此处”);
tempItem.completed=!tempItem.completed
}
退货项目;
}
);
返回{todos:updatedToDos};
});
}
在React.Strict模式下,状态更新程序将被调用两次。参考这个答案
将您的handleChange函数更新到下面
handleChange(id){
const todos=[…this.state.todos];
常量newTodo=todos.map((todo)=>{
if(todo.id==id){
console.log(!todo.completed);
todo.completed=!todo.completed;
}
返回待办事项;
});
控制台日志(newTodo);
this.setState({todos:newTodo});
}