javascript - 更新平面列表、拉取刷新、警告:列表中的每个子项都应具有唯一的“键”
问题描述
谢谢你的帮助...
我正在尝试添加一个具有拉刷新能力的平面列表。
我发布到 Firebase 的操作和显示 userPosts 的平面列表在单独的配置文件屏幕上工作(通过自动更新 redux 状态更改而不是拉到刷新)。
控制台记录“allPosts before”和“allPosts after”显示 Firebase 响应数组正在更新。就像现在的代码一样,当拉动刷新时,会弹出一个空白帖子,就好像它知道它已更新但值或格式未对齐。
任何帮助将不胜感激。再次感谢。-马特
Warning: Each child in a list should have a unique "key" prop.%s%s See /fb.me/react-warning-keys for more information.%s, Check the render method of `VirtualizedList`.
行动:
//get first five posts
export const getPosts = () => {
return async (dispatch) => {
try {
const posts = await Fire.shared.db.collection('posts').orderBy("timestamp", "desc").limit(5).get() //get all the posts'
let array = []
posts.forEach((post) => {
array.push(post.data())
})
dispatch({ type: 'GET_POSTS', payload: array })
} catch (e) {
console.error(e)
}
}
}
//get additional posts
export const addPostsBefore = (getState) => {
return async (dispatch, getState) => {
try {
console.log("array.allPosts before addPostsBefore: " + JSON.stringify(getState().feed.allPosts.length) )
const posts = await Fire.shared.db.collection('posts').where('timestamp', '>=', getState().feed.allPosts[0].timestamp).orderBy("timestamp", "asc").limitToLast(10).get()
if (posts) {
console.log("Firebase response to be added: " + posts )
let array = []
posts.forEach((post) => {
array.push(post.data())
})
console.log("array.length: " + array.length )
dispatch({ type: 'TO_BE_ADDED', payload: array })
console.log("array.allPosts after addPostsBefore: " + JSON.stringify(getState().feed.allPosts.length) )
} else {
return null
}
} catch (e) {
console.error(e)
}
}
}
减速器:
let feedDefaultState = {}
const feed = (state = feedDefaultState, action) => {
switch (action.type) {
case 'TO_BE_ADDED':
return {...state, allPosts: [action.payload, ...state.allPosts]}
case 'GET_POSTS':
return { ...state, allPosts: action.payload }
default:
return state
}
}
屏幕/平面列表:
<FlatList
data={this.props.feed.allPosts}
onRefresh={this.handleRefresh}
refreshing={false}
keyExtractor={(item) => item.id}
renderItem={({ item }) =>
<View><Text>{item.postDescription}</Text></View>
}
/>```
解决方案
您需要key
在由renderItem
. 这是反应所需要的优化
<FlatList
data={this.props.feed.allPosts}
onRefresh={this.handleRefresh}
refreshing={false}
keyExtractor={(item) => item.id}
renderItem={({ item }) =>
<View key={item.id}><Text>{item.postDescription}</Text></View>
}
/>
推荐阅读
- rust - PartialEq 和 PartialOrd 实现不返回正确的输出
- angular - 如何在角度 11 中绑定到数组
- sql - 在 Oracle DBMS 中使用多个嵌套查询
- c# - ASP.NET 身份关系
- android - 如何在 Drawer 中使用 StreamBuilder?
- python - 我可以创建一个矩形表面并在其上绘制一个文本并在 pygame 中将这些对象拼凑在一起吗
- c# - Xamarin 中的随机图像
- function - 如何通过点击原生反应中的 touchableOpacity 来开始倒计时?
- c# - 如何访问另一个查询 LINQPad 的成员?
- oauth - 如何使用 instagram API 登录