gpt4 book ai didi

reactjs - React hook useState(初始化函数)被调用了两次,即使根本没有改变数据?

转载 作者:行者123 更新时间:2023-12-02 19:15:33 26 4
gpt4 key购买 nike

在这里in this example我只是用初始化函数调用 useState:

import React, { useState } from "react";
import "./styles.css";

export default function App() {
const [data, setData] = useState(() => {
console.log('Getting initial state...');

return {};
});

return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}

从控制台可以看出,useState 函数被调用了两次。这有什么原因吗,这是正常行为吗?

最佳答案

这是由 Strict Mode 引起的,它正在包装您的 App

在严格模式下,React 有意运行一些生命周期方法两次以帮助检测错误。

来自docs :

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:

Class component constructor, render, and shouldComponentUpdate methodsClass component static getDerivedStateFromProps methodFunction component bodiesState updater functions (the first argument to setState)Functions passed to useState, useMemo, or useReducer

Note:This only applies to development mode. Lifecycles will not be double-invoked in production mode.

关于reactjs - React hook useState(初始化函数)被调用了两次,即使根本没有改变数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63762534/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com