gpt4 book ai didi

javascript - 为什么console.log中的内容在react native return语句中无限次打印

转载 作者:行者123 更新时间:2023-12-05 04:25:48 24 4
gpt4 key购买 nike

我是 React Native 的新手,我只想检查函数返回语句中的 console.log 语句,但是当我检查控制台时,console.log 的内容会在控制台选项卡中无限打印。谁能解释为什么会这样?下面是我正在检查的代码,在此先感谢。

import * as React from'react';
import { Text, View } from 'react-native';
function ExportFile() {
var RNFS = require('react-native-fs');
return (
<View>
<Text>
ExportFile
{
console.log("hello")

}
</Text>
</View>
);
}

export default ExportFile;

下面是我的控制台输出。

Console-output

最佳答案

这是因为组件一直在重新渲染。每次重新呈现时,都会再次记录该语句。您最好将 console.log 移至 useEffect。像这样的东西:

import * as React from'react';
import { Text, View } from 'react-native';

function ExportFile() {
//only call console.log on component mount
React.useEffect(()=>{
console.log("hello")
},[])

var RNFS = require('react-native-fs');
return (
<View>
<Text>
ExportFile
</Text>
</View>
);
}

export default ExportFile;

这只会在组件挂载时使用 console.log。您当然可以将依赖项添加到 useEffect 以根据依赖项更改进行登录。有关更多信息,请查看官方文档:https://reactjs.org/docs/hooks-effect.html

关于javascript - 为什么console.log中的内容在react native return语句中无限次打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73170004/

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