React Native请求谷歌日历数据后setState未触发页面重渲染如何解决
问题原因&解决方案
React 的 useState 更新本身就会自动触发页面重渲染,不需要额外手动触发,页面没有刷新是代码逻辑错误导致的,问题点和修正方案如下:
1. 状态赋值位置错误
你把setCalendarEvents写在了遍历事件的map循环内部,应该等所有符合条件的事件都筛选完成后,再统一给状态赋值,避免不必要的重复更新。
2. 渲染逻辑没有返回值
你写的calendarEvents.map用了大括号包裹渲染逻辑,但是没有加return语句,导致遍历后返回的是空数组,自然不会渲染任何内容。
3. 字段存在性判断逻辑错误
typeof运算符返回的是字符串,你写的typeof event["start"].dateTime !== undefined永远为真,无法正确筛选包含dateTime字段的事件。
4. 非法渲染对象
你直接把event对象放在<View>中渲染,React Native 不支持直接渲染 JS 对象,需要取具体字段展示。
修正后的代码
请求处理部分:
const calendarData = async function signInWithGoogleAsync() { try { const result = await Google.logInAsync({ androidClientId: `['CLIENT ID]`, iosClientId: `['CLIENT ID']`, scopes: [ "profile", "email", "https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.events", ], }); if (result.type === "success") { axios({ method: "get", baseURL: "https://www.googleapis.com/calendar/v3/calendars/['USER CALENDAR]/events?key=['API KEY']", headers: { Authorization: "Bearer " + result.accessToken, Accept: "application/json", }, }) .then((response) => { // 筛选符合条件的事件 const responseDataArray = response.data.items.filter(event => { // 直接判断dateTime是否存在 return !!event.start?.dateTime }) // 筛选完成后统一更新状态 setCalendarEvents(responseDataArray); }) .catch((error) => console.log(error)); } else { return { cancelled: true }; } } catch (e) { return { error: true }; } };
页面渲染部分:
return ( <View> {calendarEvents.map((event, index) => { // 必须加return返回要渲染的组件,取需要展示的字段渲染 return <View key={index}>{event.summary} - {event.start.dateTime}</View> })} </View> )
内容的提问来源于stack exchange,提问作者Matt Laszcz
相关产品推荐
相关产品推荐

