作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在使用 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
,这就是错误状态更新发生的地方。
要解决此问题,请从 TodoApp
的 handleRemove
方法返回一个更新状态的函数。简化版:
handleRemove(id) {
return () => {
...
this.setState({ data: remainder });
}
}
这里还值得注意的是,因为您使用的是当前状态,所以最好使用 setState
回调(它获取 prevState
作为参数),而不是依赖在 this.state
上。
关于javascript - react : Cannot update during an existing state transitio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44292866/
我在使用 React 时遇到问题。当我按下“+”按钮时,出现此控制台消息,但没有任何反应: Cannot update during an existing state transition (suc
我是一名优秀的程序员,十分优秀!