Мое приложение загружает сообщения Wordpress через wp_ json api и обновляет их в плоском списке. Если какой-либо пользователь нажимает на любой элемент, он открывается на новой странице. Однако этот функционал временно не работает, если он находится в процессе загрузки сообщений с сервера или кеша. Т.е. событие onPress не работает, если приложение получает данные с сервера или кеша.
Home. js
import React, { useState, useEffect } from 'react';
import * as P from 'react-native-paper';
import { View, Text, StyleSheet, Image, FlatList, Alert } from 'react-native';
import ViewPost from './ViewPost';
import axios from 'axios';
import config from '../../package.json';
import { useSelector, useDispatch } from 'react-redux';
import {AllHtmlEntities} from 'html-entities';
import moment from 'moment';
import * as AS from '../Lib/Storage';
import AsyncStorage from '@react-native-community/async-storage';
import PostCard from './PostCard';
import DeepLinkingComponent from '../DeepLinkingComponent';
import cache from '../Lib/ModestCache';
const Home = (props) => {
const [postList, setPostList] = useState([]);
const [currentPage, setCurrentPage] = useState(0);
const [isLoading, setIsLoading] = useState(false);
let state = useSelector(state => state);
let theme = P.useTheme();
let dispatch = useDispatch();
useEffect(()=>{
if(state.AppState.category !== -1){
loadMore(false);
}
},[state.AppState.language, state.AppState.category])
const loadMore = (append=true) => {
let newPage = 1;
if(append){
newPage = currentPage+1;
}
let sticky = false;
let url = config.apiBaseUrl+"/wp/v2/posts?lang="+state.AppState.language+"&per_page=20&page="+(newPage-1)
if(state.AppState.category > 0){
url = config.apiBaseUrl+"/wp/v2/posts?categories[]="+state.AppState.category+"&per_page=20&lang="+state.AppState.language+"&page="+newPage
}
if(newPage == 1 && state.AppState.category == 0){
sticky = true;
url = config.apiBaseUrl+"/wp/v2/posts?lang="+state.AppState.language+"&per_page=50&sticky=true"
}
setIsLoading(true);
const displayPostData = (r,sticky) => {
// console.log("Sticky: "+sticky);
// if(sticky == false){
if(state.GlobalState.isLoading){
dispatch({type:"GS/LOADING_STOP"});
}
if(state.SplashState === "FIRST"){
dispatch({type:"SPLASH/SHOWED"});
}
// }
if(append){
setPostList(postList.concat(r.data));
} else {
setPostList(r.data);
}
setCurrentPage(newPage);
setIsLoading(false);
}
cache.get(url).then((r)=>{
if(r === undefined){
axios.get(url).then((r)=>{
displayPostData(r,sticky);
cache.set(url,r);
AsyncStorage.setItem(url,JSON.stringify(r));
}).catch((e)=>{
AsyncStorage.getItem(url).then( (r) =>{
if(r!==null && r !==undefined){
r = JSON.parse(r);
displayPostData(r,sticky);
} else {
if(e.response !== undefined){
if(e.response.status !== 400){
alert("No Internet. Error Code: "+e.response.status);
}
} else {
dispatch({type:"GS/LOADING_STOP"});
alert("No Internet");
}
}r
setIsLoading(false);
}).catch((c) => {
console.log(c);
});
});
} else {
displayPostData(r,sticky);
}
})
}
return <>
<DeepLinkingComponent />
<FlatList
data={postList}
renderItem={({ item, index, separators }) => <PostCard postList={postList} {...item} theme={theme} index={index} {...props} /> }
keyExtractor={r => r.id+"-"+Math.random().toString()}
onEndReachedThreshold={20}
removeClippedSubviews={true}
maxToRenderPerBatch={2}
ListFooterComponent={<P.ActivityIndicator size="small" color={theme.colors.primary} style={{
alignSelf:"center", padding:10,
}} animating={isLoading}></P.ActivityIndicator>}
onEndReached={()=>{
loadMore() ;
}}
/>
</>
}
export default Home;
PostCard. js (В этом файле см. OnPressHandler (). Он не срабатывает, пока «Home. js» загружает данные с сервера / кеш)
import React, { pure } from 'react';
import * as P from 'react-native-paper';
import { View, Text, StyleSheet, Image, FlatList, Alert } from 'react-native';
import ViewPost from './ViewPost';
import axios from 'axios';
import config from '../../package.json';
import {AllHtmlEntities} from 'html-entities';
import moment from 'moment';
import * as AS from '../Lib/Storage';
import AsyncStorage from '@react-native-community/async-storage';
import * as AD from '../AdSystem';
import { TouchableNativeFeedback } from 'react-native-gesture-handler';
export default class PostCard extends React.PureComponent {
onPressHandler(){
let data = {
title: this.props.title.rendered,
content: this.props.content.rendered,
//image: this.props.featuredimage.source,
image: this.props.jetpack_featured_media_url,
date:this.props.date,
link:this.props.link,
id:this.props.id,
rawdata:JSON.stringify(this.props)
}
this.props.navigation.navigate("View",{
...data
})
AD.interstitial.load();
}
render(){
let image = <></>
if(this.props.jetpack_featured_media_url.trim() !== ""){
image = <Image style={{flex:1}} source={{
//uri: this.props.featuredimage,
uri: this.props.jetpack_featured_media_url,
}} />
}
// console.log(this.props.jetpack_featured_media_url);
let theme = this.props.theme;
return <TouchableNativeFeedback onPress={() => onPressHandler()}><P.Card style={{margin:10}}>
<P.Card.Content>
<Text style={{fontSize:17, lineHeight:23, fontWeight:"600", color:theme.colors.accent}}>{AllHtmlEntities.decode(this.props.title.rendered)}</Text>
<Text style={{fontSize:12, lineHeight:23, color:"gray"}}>Published On {moment(this.props.date).format("DD MMM YYYY")}</Text>
<View style={{flexDirection:"row"}}>
<View style={{flex:2, marginRight:10, marginTop:10}}>
{image}
</View>
<View style={{flex:5}}>
<P.Paragraph>{AllHtmlEntities.decode(this.props.excerpt.rendered).replace(/<[^>]+>/g, '').substr(0,150)}...</P.Paragraph>
</View>
</View>
</P.Card.Content>
</P.Card></TouchableNativeFeedback>
}
}
/*
function PostCard (props) {
// const Entities = require('html-entities').AllHtmlEntities;
const onPress = () => {
let data = {
title: props.title.rendered,
content: props.content.rendered,
//image: props.featuredimage.source,
image: props.jetpack_featured_media_url,
date:props.date,
link:props.link,
id:props.id,
rawdata:JSON.stringify(props)
}
AD.interstitial.load();
props.navigation.navigate("View",{
...data
})
}
let image = <></>
if(props.jetpack_featured_media_url.trim() !== ""){
image = <Image style={{flex:1}} source={{
//uri: props.featuredimage,
uri: props.jetpack_featured_media_url,
}} />
}
// console.log(props.jetpack_featured_media_url);
let theme = P.useTheme();
return <P.Card onPress={() => onPress()} style={{margin:10}}>
<P.Card.Content>
<Text style={{fontSize:17, lineHeight:23, fontWeight:"600", color:theme.colors.accent}}>{AllHtmlEntities.decode(props.title.rendered)}</Text>
<Text style={{fontSize:12, lineHeight:23, color:"gray"}}>Published On {moment(props.date).format("DD MMM YYYY")}</Text>
<View style={{flexDirection:"row"}}>
<View style={{flex:2, marginRight:10, marginTop:10}}>
{image}
</View>
<View style={{flex:5}}>
<P.Paragraph>{AllHtmlEntities.decode(props.excerpt.rendered).replace(/<[^>]+>/g, '').substr(0,150)}...</P.Paragraph>
</View>
</View>
</P.Card.Content>
</P.Card>
}
export default pure(PostCard);*/