React 报错: Cannot update a component (`App`) while rendering a different component (`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.\n\nTo 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.\n\nHere is an example of how you can fix this issue:\n\nIn the App component:\njsx\nimport React, { Component } from 'react';\nimport Todo from './Todo';\n\nclass App extends Component {\n constructor(props) {\n super(props);\n this.state = {\n todos: [],\n };\n }\n\n componentDidMount() {\n // Fetch todos from API or initialize the state\n // Update the state here\n this.setState({ todos: ['Todo 1', 'Todo 2', 'Todo 3'] });\n }\n\n render() {\n return (\n <div>\n <h1>Todos</h1>\n <Todo todos={this.state.todos} />\n </div>\n );\n }\n}\n\nexport default App;\n\n\nIn the Todo component:\njsx\nimport React from 'react';\n\nconst Todo = ({ todos }) => {\n // Render todos here\n return (\n <ul>\n {todos.map((todo, index) => (\n <li key={index}>{todo}</li>\n ))}\n </ul>\n );\n};\n\nexport default Todo;\n\n\nBy 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.
原文地址: https://www.cveoy.top/t/topic/qc07 著作权归作者所有。请勿转载和采集!