在我的简单 react 应用程序中,有两个组件:App
和 Comments
。
App.js =>
import Comments from "./comments/Comments";
const App = () => {
return (
<div>
<h1>App.js</h1>
<Comments currentUserId="1" />
</div>
);
};
export default App;
Comments.js =>
import { useState, useEffect } from "react";
import { getComments as getCommentsApi } from "../api";
const Comments = ({ currentUserId }) => {
const [comments, setComments] = useState([]);
console.log("Comments", comments);
useEffect(() => {
getCommentsApi()
.then(data => {
setComments(data);
})
}, []);
return (
<div>
<h1>Comments.js</h1>
</div>
);
};
export default Comments;
如果你看一下我的评论组件,我会在函数体中记录评论,它应该执行两次,第一次是初始加载,第二次是由于 useEffect 和更改状态。
React 组件应在 props 或状态更改时重新执行
但是我的控制台中出现了 4 条日志。为什么?
最佳答案
我认为您正在使用严格模式,这就是您得到意外结果的原因。从index.js 文件中删除严格模式组件,代码将按预期工作
关于reactjs - React 组件重新执行错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73011626/