React Native 各种坑

FlatList 报错 keyExtractor 未指定唯一的 key
1
VirtualizedList: missing keys for items, make sure to specify a key property on each item or provide a custom keyExtractor.

keyExtractor 用于为给定的item生成一个不重复的key。若不指定此函数,则默认抽取item.key作为key值。若item.key也不存在,则使用数组下标index。

解决方法:
添加 _keyExtractor = (item, index) => index;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
renderLoadingView() {
...
}
_keyExtractor = (item, index) => index;
renderMovie(movie) {
...
}
render() {
<FlatList
...
keyExtractor={this._keyExtractor}
/>
}
React Native中文网电影列表示例中的错误

上边”FlatList 报错 keyExtractor 未指定唯一的 key“是其中一个问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
renderMovie(movie) {
console.log(movie)
return (
<View style={styles.container}>
<Image
source={{uri: movie.posters.thumbnail}}
style={styles.thumbnail}
/>
<View style={styles.rightContainer}>
<Text style={styles.title}>{movie.title}</Text>
<Text style={styles.year}>{movie.year}</Text>
</View>
</View>
);
}

请求到数据后按照示例上边这种写法会一直黄色 warning ,提示:

1
2
3
Possible Unhandled Promise Rejection (id: 0):
TypeError: Cannot read property 'thumbnail' of undefined
TypeError: Cannot read property 'thumbnail' of undefined

这时候打印请求到的 movie 是这样的:


所以,真实数据应该是 movie.item

1
2
3
4
5
6
7
8
9
10
11
12
13
14
renderMovie(movie) {
return (
<View style={styles.container}>
<Image
source={{uri: movie.item.posters.thumbnail}}
style={styles.thumbnail}
/>
<View style={styles.rightContainer}>
<Text style={styles.title}>{movie.item.title}</Text>
<Text style={styles.year}>{movie.item.year}</Text>
</View>
</View>
);
}
ReactNative:The development server returned response error code: 500。
1
I'm making react-native app with my frd. So I got the code my frd first made and I wanted to open my computer. I think I set everything and did tcp:8081 setting in dev menu. but I got error message after started react-native packager. I use real phone device.

运行 ReactNative 项目时出现500的错误,最后通过给 babel-preset-react-native 降级或者安装来解决了这个问题。

1
2
3
4
//npm
npm install babel-preset-react-native@2.1.0 —save
//yarn
yarn add babel-preset-react-native@2.1.0

记得安装后要重启项目。