首页 > 解决方案 > 反应日志运行两次

问题描述

我是 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 中查看日志时,我注意到它执行了两次而不是一次,这是为什么呢?

标签: reactjsreact-native

解决方案


因为您的组件重新渲染了两次:

  1. 初始化状态时
  2. 当状态更新时。

因此,可以这么说,您在组件主体中的代码会重新执行。


推荐阅读