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