我正在研究 ReactJs 并遇到一些问题。我的问题是我有一个使用最新 ReactJs(v 18.0.0)的简单应用程序,并且 componentDidMount 执行两次。为什么?
index.js
import { createRoot } from 'react-dom/client';
import './index.css';
import App from './App';
const container = document.getElementById('root');
const root = createRoot(container);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
App.js
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
monsters: []
};
}
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => this.setState({ monsters: users }));
}
render() {
return (
<div className="App">
{this.state.monsters.map(monster =>
<h1 key={monster.id}>{monster.name}</h1>
)}
</div>
);
}
}
export default App;```
最佳答案
在 React 版本 18 中,对严格模式进行了更改,以便组件将安装,然后卸载,然后再次安装。添加此内容是为了帮助我们所有人开始发现将影响即将推出的功能的问题。在 React 的 future 版本中,状态将能够在卸载之间保留,因此组件可能会挂载多次。
在大多数情况下,您现在可以忽略双安装。但如果您愿意,您可以开始为将来编写代码,以便您的组件检查它之前是否已经安装并跳过获取:
componentDidMount() {
if (this.fetchPromise) {
// already mounted previously
return;
}
this.fetchPromise = fetch('https://jsonplaceholder.typicode.com/users'
.then(response => response.json())
.then(users => this.setState({ monsters: users }));
}
关于javascript - ReactJs componentDidMount 执行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71755119/