React 调用构造函数两次 [英] React calls constructor twice

查看:90
本文介绍了React 调用构造函数两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 React 新手,我正在尝试用它开发一个简单的 Web 应用程序,但出现错误.当我加载一个类组件时,我的构造函数被调用了两次你能帮忙吗?

I am new to react and I am trying to develop a simple web app with it but I get an error. My Constructor is called twice when I load a class component can you help?

Home.js


import React from 'react'
import Land from "../Land";

function Home() {
    return (
        <div>
            <h1>Home!</h1>
            <Land/>
        </div>
    )
}

export default Home

)}导出默认首页

the log LAND is hit twice.
In some of the components I wish to make an API call that hits a DB but I only want to hit it once.
In many instances using componentDidMount is not convenient because props only appear after componentDidMount therefor id like to do the call in render(I will not be using setState, that would cause a reload of render).

原木 LAND 被击中两次.在某些组件中,我希望进行命中数据库的 API 调用,但我只想命中一次.在许多情况下,使用 componentDidMount 并不方便,因为 props 只出现在 componentDidMount 之后,因此 id 喜欢在 render 中进行调用(我不会使用setState,这会导致重新加载渲染).

Thanks in advance

提前致谢

推荐答案

您正在使用 和它的开发模式

中,react 将 检测意外的副作用,这将在开发模式期间多次调用生命周期函数,在生产中不会被触发两次.

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 methods

类组件构造函数、render 和 shouldComponentUpdate 方法

Class component static getDerivedStateFromProps method

类组件静态 getDerivedStateFromProps 方法

Function component bodies

函数组件主体

状态更新器函数(setState 的第一个参数)

Functions passed to useState, useMemo, or useReducer

传递给 useState、useMemo 或 useReducer 的函数

will not call twice

不会调用两次

<块引用>

注意:

Note:

这仅适用于开发模式.生命周期不会在生产模式下被双重调用.

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

这篇关于React 调用构造函数两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆