react 报错Cannot update a component App while rendering a different component Todo To locate the bad setState call inside Todo
The error message "Cannot update a component (App) while rendering a different component (Todo). To locate the bad setState() call inside Todo" occurs when you are trying to update the state of the App component while rendering the Todo component.
To fix this issue, you need to ensure that you are not calling setState inside the Todo component during its rendering phase. Instead, you should move the setState call to a different lifecycle method or event handler outside of the rendering phase.
Here is an example of how you can fix this issue:
In the App component:
import React, { Component } from 'react';
import Todo from './Todo';
class App extends Component {
constructor(props) {
super(props);
this.state = {
todos: [],
};
}
componentDidMount() {
// Fetch todos from API or initialize the state
// Update the state here
this.setState({ todos: ['Todo 1', 'Todo 2', 'Todo 3'] });
}
render() {
return (
<div>
<h1>Todos</h1>
<Todo todos={this.state.todos} />
</div>
);
}
}
export default App;
In the Todo component:
import React from 'react';
const Todo = ({ todos }) => {
// Render todos here
return (
<ul>
{todos.map((todo, index) => (
<li key={index}>{todo}</li>
))}
</ul>
);
};
export default Todo;
By moving the setState call to the componentDidMount lifecycle method of the App component, you ensure that it is not called during the rendering phase of the Todo component
原文地址: http://www.cveoy.top/t/topic/ivuL 著作权归作者所有。请勿转载和采集!