为什么代码内部使用效果在第一个渲染中运行两次?
Console.Log运行两次。下面说是原因严格模式
:
react Hooks:useEffect()即使将空数组用作参数也被称为两次
strictmode在 为了检测您的代码问题并警告您 (这很有用)。
但是我不明白为什么!它说:为了检测您的代码问题并警告您
。但是哪个问题?警告什么?
,是否有一种方法可以摆脱(两次运行)而不删除应用程序中的严格模式?
是我的代码:
import {useEffect, useState} from "react";
import BlogList from "./BlogList";
const Home = () =>{
const [blogs, setBlogs] = useState([
{ title: 'My new website', body: 'lorem ipsum...', author: 'mario', id: 1 },
{ title: 'Welcome party!', body: 'lorem ipsum...', author: 'yoshi', id: 2 },
{ title: 'Web dev top tips', body: 'lorem ipsum...', author: 'mario', id: 3 }
]);
const [name, setName] = useState('mario');
const handleDelete = (id) => {
const newBlogs = blogs.filter(blog => blog.id !== id);
setBlogs(newBlogs);
}
useEffect(() => {
console.log("useEffect is run");
console.log(name);
},[name]);
return(
<div className="Home">
<BlogList blogs={blogs} title="All Blogs" handleDelete={handleDelete} />
<button onClick={() => setName('arman')}>Delete name</button>
<p>{name}</p>
</div>
);
}
export default Home;
完整的代码:
Console.log runs twice. Underneath said it is to reason Strict Mode
:
React Hooks: useEffect() is called twice even if an empty array is used as an argument
StrictMode renders components twice (on dev but not production) in
order to detect any problems with your code and warn you about them
(which can be quite useful).
But I don't understand why! It says: in order to detect any problems with your code and warn you about them
. But which is the problem? And warning about what thing?
And is there a way for rid of that(twice running) without removing Strict Mode
from the app?
It's my code:
import {useEffect, useState} from "react";
import BlogList from "./BlogList";
const Home = () =>{
const [blogs, setBlogs] = useState([
{ title: 'My new website', body: 'lorem ipsum...', author: 'mario', id: 1 },
{ title: 'Welcome party!', body: 'lorem ipsum...', author: 'yoshi', id: 2 },
{ title: 'Web dev top tips', body: 'lorem ipsum...', author: 'mario', id: 3 }
]);
const [name, setName] = useState('mario');
const handleDelete = (id) => {
const newBlogs = blogs.filter(blog => blog.id !== id);
setBlogs(newBlogs);
}
useEffect(() => {
console.log("useEffect is run");
console.log(name);
},[name]);
return(
<div className="Home">
<BlogList blogs={blogs} title="All Blogs" handleDelete={handleDelete} />
<button onClick={() => setName('arman')}>Delete name</button>
<p>{name}</p>
</div>
);
}
export default Home;
The complete code:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
StrictMode渲染组件两次,以检测开发过程中代码的任何问题。您应该在生产上没事。如果您绝对不想要双渲染,请删除标签。
StrictMode renders components twice in order to detect any problems with your code during development. You should be fine in production. If you absolutely don't want the double render then just remove the tag.
React Docs: Strict Mode