繁体   English   中英

组件渲染两次

[英]Component is rendering twice

我正在关注一个教程,刚刚了解了useEffect 我遇到的问题是我想得到result.hours[0].is_open_now 我发现该组件渲染了两次,并且由于最初未定义小时数,因此它失败了。

有没有办法让它只运行一次。

const ResultsShowScreen = ({ navigation }) => {

    const id = navigation.getParam('id');
    const [result, setResult] = React.useState({})

    const getResult = async (id) => {
       const response = await yelp.get(`/${id}`)
       setResult(response.data)
    }

    useEffect(() => {
        getResult(id)
     }, [])

    if (!result || result.length <= 0) {
        return null
    }

     const {name, 
            display_address, 
            price,
            display_phone,
            photos,
            review_count,
            rating,
            hours          
        } = result

        if (hours && hours.length > 0 ) {
            const is_open_now = hours[0].is_open_now
            console.log('running')
        } else {
            console.log('nooooo')
        }

    return (
        <View> 

            <Text style={styles.title}>{name}</Text>

            <Text>Price: {price}</Text>
            <Text>Rating: {rating}</Text>
            <Text>Reviews: {review_count}</Text>
            <Text>Phone: {display_phone}</Text>
            <Text>Is Open Now: </Text>
        </View>
    )

}

export default ResultsShowScreen

按照您的代码,您不能阻止useEffect渲染两次,因为遵循反应钩子生命周期

如果您熟悉 React class 生命周期方法,您可以将 useEffect Hook 视为 componentDidMount、componentDidUpdate 和 componentWillUnmount 的组合。

这意味着useEffect将在组件第一次渲染后执行(您的代码第一次为空),如果第二个参数有值则执行更多时间。

在你的useEffect中,你调用setState来设置新的 state 和如果 state 改变组件自动渲染。 所以你的组件将至少被渲染两次。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM