Skip to content

Instantly share code, notes, and snippets.

@singleseeker
Created December 3, 2018 03:56
Show Gist options
  • Save singleseeker/f629b9226c41c0c482619b0d6f832ae6 to your computer and use it in GitHub Desktop.
Save singleseeker/f629b9226c41c0c482619b0d6f832ae6 to your computer and use it in GitHub Desktop.
could not get geo info when loaded first
import React, {PureComponent} from 'react'
import {Platform, AppState, Alert} from 'react-native'
import styled from 'styled-components'
import PropTypes from 'prop-types'
import axios from 'axios'
import Permissions from 'react-native-permissions'
import {TYPE, SORT} from '@utils/constants'
import {
ShopList,
ShowcaseImage,
Picker,
Gradient,
} from '@components'
import { defaults} from '@utils/images'
import API from '@utils/api'
const FlatList = styled.FlatList`
flex: 1;
`
const Row = styled(Gradient)`
flex-direction: row;
justify-content: space-between;
`
class DiscoverByType extends PureComponent {
static propTypes = {
navigation: PropTypes.object.isRequired,
}
static navigationOptions = ({navigation}) => ({
title: navigation.getParam('title', '全部'),
headerStyle: {
shadowColor: 'transparent',
borderBottomWidth: 0,
elevation: 0,
},
})
_isMounted = false
state = {
type: this.props.navigation.getParam('title', '全部'),
cat: this.props.navigation.getParam('cat', ''),
sort: 'ai',
order_gps : '',
shops: [],
page: 1,
current: {},
}
async componentDidMount() {
this._isMounted = true
await this.updatePermissions()
await this.getData()
AppState.addEventListener('change', this.handleAppStateChange)
}
componentWillUnmount() {
this._isMounted = false
AppState.removeEventListener('change', this.handleAppStateChange)
}
getData = async () => {
try {
const {cat, sort, order_gps} = this.state
this.setState({shops: []})
console.warn(order_gps)
const payload = await axios.request(
API.GET.shops({cat, order: sort,gps : order_gps, page: 1}),
)
if (this._isMounted) {
this.setState({
shops: payload.data.data || [],
page: 1,
total: payload.data.meta.pagination.total_pages,
})
}
} catch (err) {
console.warn(err)
}
}
getMoreData = async () => {
const {cat, sort, page, total} = this.state
try {
if (page < total) {
const payload = await axios.request(
API.GET.shops({cat, order: sort, page: page + 1}),
)
if (this._isMounted) {
this.setState(prev => ({
shops: prev.shops.concat(payload.data.data || []),
page: prev.page + 1,
}))
}
}
} catch (err) {
console.warn(err)
}
}
handleAppStateChange = appState => {
if (appState === 'active') {
this.updatePermissions()
}
}
openSettings = () => Permissions.openSettings()
requestLocation = async () => {
const result = await Permissions.request('location')
this.getLocation(result)
}
getLocation = result => {
console.warn(result)
const that = this;
if (result === 'authorized') {
navigator.geolocation.getCurrentPosition(
pos =>
this._isMounted &&
this.setState({locationServices: true, current: pos.coords,order_gps:`${pos.coords.longitude}_${pos.coords.latitude}`},()=>{
}),
(error: any) => {
console.warn(`失败:${ JSON.stringify(error.message)}`)
},
// error => this._isMounted && this.setState({error: error.message}),
{enableHighAccuracy: false, timeout: 20000, maximumAge: 1000},
)
}
}
updatePermissions = async () => {
try {
const result = await Permissions.check('location')
const buttons = [{text: '取消', style: 'cancel'}]
switch (result) {
case 'undetermined':
this.requestLocation()
break
case 'authorized':
this.getLocation(result)
break
case 'restricted':
case 'denied':
default:
if (await Permissions.canOpenSettings())
buttons.push({
text: '设定',
onPress: this.openSettings,
})
Alert.alert(
'所在地权限',
'为了更好的商铺推荐体验,我们需要您的当前所在位置信息',
buttons,
)
}
} catch (err) {
console.warn(err)
}
}
goto = (route, params = {}) => {
this.props.navigation.navigate(route, params)
}
handleChangeCategory = itemValue => {
this.requestLocation()
this.setState({cat: itemValue},()=>{
if (Platform.OS === 'android') {
this.getData()
}
})
let that = this
TYPE.map((userData) => {
console.log(userData);
if( userData.key === itemValue ){
that.props.navigation.setParams({
title:userData.label
})
}
});
}
handleChangeSorting = value => {
this.setState({sort: value,gps: this.state.order_gps},()=>{
if (Platform.OS === 'android') {
this.getData()
}
})
}
handleDone = () => this.getData()
renderItem = ({item}) =>
item.id === 'filter' ? (
<Row key="filter">
<Picker
onDonePress={this.handleDone}
selected={this.state.cat}
items={TYPE}
handleChange={this.handleChangeCategory}
placeholder={{
label: '全部',
value: '',
}}
/>
<Picker
onDonePress={this.handleDone}
selected={this.state.sort}
items={SORT}
handleChange={this.handleChangeSorting}
/>
</Row>
) : (
<ShopList
item={item}
handlePressed={() => this.goto('ShopDetail', {shop: item, id: item.id})}
/>
)
renderMap = () => (
<ShowcaseImage key="map" image={defaults.map} handlePressed={() => {}} />
)
render() {
const {shops} = this.state
return (
<FlatList
ListHeaderComponent={this.renderMap}
stickyHeaderIndices={[1]}
data={[{id: 'filter'}, ...shops]}
renderItem={this.renderItem}
keyExtractor={item => item.id}
onEndReached={this.getMoreData}
onEndReachedThreshold={0.5}
maxToRenderPerBatch={4}
initialNumToRender={8}
/>
)
}
}
export default DiscoverByType
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment