reactjs - 反应日志运行两次
问题描述
我是 React 的新手,想知道为什么 console.log() 在我运行我的应用程序时执行了两次?
import React, { useState } from 'react';
import { View, Text, StyleSheet, ScrollView } from 'react-native';
import SearchBar from '../components/SearchBar';
import useResults from '../hooks/useResults';
import ResultsList from '../components/ResultsList';
const SearchScreen = () => {
const [ term, setTerm ] = useState( '' ),
[ searchApi, results, errorMessage ] = useResults();
const filterResultsByPrice = ( price ) => {
return results.filter( result => {
return result.price === price;
} );
}
console.log( results[0].name ); // Is being printed twice. Why?
return (
<View style={ { flex: 1 } }>
<SearchBar
term={ term }
onTermChange={ setTerm }
onTermSubmit={ () => searchApi( term ) }
/>
{ errorMessage ? <Text>{ errorMessage }</Text> : null }
<Text>We have found { results.length } results.</Text>
<ScrollView>
<ResultsList title="Cost Effective" results={ filterResultsByPrice( '$' ) } />
<ResultsList title="Bit Pricier" results={ filterResultsByPrice( '$$' ) } />
<ResultsList title="Big Spender" results={ filterResultsByPrice( '$$$' ) } />
<ResultsList title="Price Unknown" results={ filterResultsByPrice( undefined ) } />
</ScrollView>
</View>
);
};
const styles = StyleSheet.create( {} );
export default SearchScreen;
当我在 Git Bash 中查看日志时,我注意到它执行了两次而不是一次,这是为什么呢?
解决方案
因为您的组件重新渲染了两次:
- 初始化状态时
- 当状态更新时。
因此,可以这么说,您在组件主体中的代码会重新执行。
推荐阅读
- alexa - 使用 ngrok 托管在 Web 服务上的 Alexa 技能:主机和端口的这种组合需要 TLS
- c++ - 从一个对象到另一个对象的 C++/SDL 角度
- c# - 控制器中的 ASP.NET Core MVC 子操作
- eloquent - 如何存储多态相关模型
- angular - 有没有办法让我的网站将第三方 cookie 声明为第一方 cookie?
- openedge - 为什么我们需要编译进度4GL的程序?
- javascript - 带有随机计时器延迟的Javascript setTimeout按顺序显示数组项
- apache-kafka - Zookeper 服务器上的连接太多
- ios - 停止任意函数执行
- laravel-5 - 如何在 namecheap 主机上上传 laravel 项目