gpt4 book ai didi

javascript - react : Cannot update during an existing state transitio

转载 作者:行者123 更新时间:2023-11-28 17:56:50 25 4
gpt4 key购买 nike

我在使用 React 时遇到问题。当我按下“+”按钮时,出现此控制台消息,但没有任何反应:

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`

我发现了几个标题相似的问题,但其中共同点是在 render 方法中调用了带有 setState 的函数。

我的渲染方法没有调用,但出现错误。

为什么?

感谢您的阅读。

代码:

import React from 'react';

const TodoForm = ({addTodo}) => {
let input;

return (
<div>
<input
ref={node => {
input = node;
}}

/>
<button onClick={() => {
addTodo(input.value);
input.value = '';
}}>
+
</button>
</div>
);
};


const Todo = ({todo, remove}) => {
// Each Todo
return (<li onClick={remove(todo.id)}>{todo.text}</li>)
};

const TodoList = ({todos, remove}) => {
// Map through the todos
const todoNode = todos.map((todo) => {
return (<Todo todo={todo} key={todo.id} remove={remove}/>)
});
return (<ul>{todoNode}</ul>);
};

const Title = () => {
return (
<div>
<div>
<h1>to-do</h1>
</div>
</div>
);
};

window.id = 0;
class TodoApp extends React.Component {
constructor(props) {
// Pass props to parent class
super(props);
// Set initial state
this.state = {
data: []
}
}

// Add todo handler
addTodo(val) {
// Assemble data
const todo = {text: val, id: window.id++}
// Update data
this.state.data.push(todo);
// Update state
console.log('setting state...');
this.setState({data: this.state.data});
}

// Handle remove
handleRemove(id) {
// Filter all todos except the one to be removed
const remainder = this.state.data.filter((todo) => {
if (todo.id !== id) return todo;
});
// Update state with filter
this.setState({data: remainder});
}

render() {
// Render JSX
return (
<div>
<Title />
<TodoForm addTodo={
(val)=>{

this.addTodo(val)
}
}/>
<TodoList
todos={this.state.data}
remove={this.handleRemove.bind(this)}
/>
</div>
);
}
}
export default TodoApp;

最佳答案

Todo 的渲染方法中,您调用 remove,这就是错误状态更新发生的地方。

要解决此问题,请从 TodoApphandleRemove 方法返回一个更新状态的函数。简化版:

handleRemove(id) {
return () => {
...
this.setState({ data: remainder });
}
}

这里还值得注意的是,因为您使用的是当前状态,所以最好使用 setState 回调(它获取 prevState 作为参数),而不是依赖在 this.state 上。

setState docs

关于javascript - react : Cannot update during an existing state transitio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44292866/

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