javascript - 组件渲染两次

标签 javascript reactjs react-native

我正在学习教程,刚刚了解了 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 hook lifecycle ,

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

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

useEffect 中,您调用 setState 来设置新状态,并在状态更改时组件自动渲染。所以你的组件将至少被渲染两次。

关于javascript - 组件渲染两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58585228/

相关文章:

angular - 从 Angular 到 React - 如何将业务逻辑与组件解耦?

javascript - React Native 无法在子元素上设置 100% 宽度

react-native - 溢出 : 'hidden' && borderRadius not working properly in React Native Android

javascript - 使用 javascript 修改超过 1 个 css 文件

javascript - React Native导入graph kit报错500

javascript - 单击图像 jQuery - 函数在附加后不起作用

node.js - 在docker中运行nodemon(MERN-docker-compose)

javascript - 如何在 React Native 中渲染 BULLET 字符?

javascript - 如何在 monthView 上隐藏事件?

javascript - 将上一页中单击的元素 html 添加到下一页上的另一个元素