我到处搜索,所有类似的帖子要么不适用,要么没有效果.我有一个非常简单的Reaction应用程序(v18.2.0),我想在我的应用程序中使用useEffect进行一些API调用和其他逻辑渲染.我的理解是,这应该只在提供空数组作为参数时触发一次.
Index.js:
import React from "react";
import App from "./src/App";
import { createRoot } from "react-dom/client";
const container = document.getElementById("root");
const root = createRoot(container);
root.render(<App />);
App.js:
import React, { useEffect } from "react";
const App = () => {
useEffect(() => {
console.log("trigger app");
}, []);
return <div />;
};
export default App;
Index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My App</title>
<script defer src="main.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
Webpack配置:
module.exports = {
mode: "development",
entry: "./index.js",
output: {
path: path.resolve(__dirname, "public"),
filename: "main.js",
},
target: ["web", "es5"],
stats: { children: true },
devServer: {
port: "9500",
static: ["./public"],
open: true,
hot: true,
liveReload: true,
},
devtool: "inline-source-map",
resolve: {
extensions: [".js", ".jsx", ".json"],
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: "babel-loader",
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: "./public/index.html",
}),
new CleanWebpackPlugin(),
],
};
查看this post,我已经验证了我没有使用严格模式,似乎没有任何触发重新渲染,该组件没有被使用一次以上.