Related
Error
Im learning react native gesture handler and react native reanimated from the docs. I got this error when i got the gesture coordinates ,passed them to the useShared value translateX. Im running my app on a Samsung Galaxy A5 2017 running android 8.0.0. Please explain your answer.
App.js
// import { StatusBar } from 'expo-status-bar';
import { useEffect } from 'react';
import { StyleSheet, Text, View,StatusBar,TouchableOpacity } from 'react-native';
import Animated, {useSharedValue, useAnimatedStyle, withTiming,withSpring,withRepeat} from 'react-native-reanimated'
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import { NavigationContainer } from '#react-navigation/native';
import Header from './components/Header';
import Gesture from './screens/Gesture';
const SimpleAnimation=({navigation})=>{
const SIZE=100.0
const handleRotation=(progress)=>{
"worklet";
return `${progress.value*2*Math.PI}rad`;
}
const progress=useSharedValue(0.5)
const scale=useSharedValue(0.5)
const reanimatedStyle=useAnimatedStyle(()=>{
return {
opacity: progress.value,
transform:[{scale:scale.value},{rotate:handleRotation(progress) }],
borderRadius:(progress.value*SIZE)/2,
};
},[])
useEffect(()=>{
progress.value=withRepeat(withSpring(1),-1,true);
scale.value=withRepeat(withSpring(2),-1,true)
},[]);
return (
<View style={{flex:1,marginTop:StatusBar.currentHeight}}>
<Header LeftComponent={()=>(<Text style={{color:"tomato",fontWeight:"bold",fontSize:20}}>Animation</Text>)} RightComponent={()=>(<TouchableOpacity onPress={()=>navigation.navigate("GestureScreen")} style={{backgroundColor:"tomato",padding:10,borderRadius:10,}}><Text style={{color:"white",fontWeight:"bold"}}>Go To Gestures</Text></TouchableOpacity>)} />
<View style={styles.container}>
<Animated.View style={[{width:SIZE,height:SIZE,backgroundColor:"blue"},reanimatedStyle]}>
</Animated.View>
</View>
</View>
);
}
const Stack = createNativeStackNavigator();
export default function App() {
const navigateTo=(screenname)=>{
}
return (
<NavigationContainer>
<Stack.Navigator initialRouteName='Animation' screenOptions={{headerShown:false}}>
<Stack.Screen name="Animation" component={SimpleAnimation}/>
<Stack.Screen name="GestureScreen" component={Gesture}/>
</Stack.Navigator>
</NavigationContainer>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Gesture.js
import { StyleSheet, Text, View,StatusBar,TouchableOpacity } from 'react-native'
import React from 'react'
import Animated,{useSharedValue,useAnimatedStyle, runOnJS} from 'react-native-reanimated'
import Header from '../components/Header'
import { Gesture,GestureDetector,GestureHandlerRootView } from 'react-native-gesture-handler'
function ActualGesture() {
const translateX=useSharedValue(0);
// const translateY=useSharedValue(0);
const gesture=Gesture.Pan().onUpdate((event)=>{
translateX=event.translationX;
});
const rStyle=useAnimatedStyle(()=>{
return {
transform:[{translateX:translateX.value}],
};
});
return (
<GestureHandlerRootView style={styles.container}>
<GestureDetector gesture={gesture}>
<Animated.View style={[styles.circle,rStyle]}></Animated.View>
</GestureDetector>
</GestureHandlerRootView>
)
}
const GestureScreen = ({navigation}) => {
return (
<View style={{flex:1,marginTop:StatusBar.currentHeight}}>
<Header LeftComponent={()=>(<TouchableOpacity onPress={()=>navigation.navigate("Animation")} style={{backgroundColor:"tomato",padding:10,borderRadius:10,}}><Text style={{color:"white",fontWeight:"bold"}}>Return</Text></TouchableOpacity>)} RightComponent={()=>(<TouchableOpacity onPress={()=>navigation.navigate("GestureScreen")} style={{backgroundColor:"tomato",padding:10,borderRadius:10,}}><Text style={{color:"white",fontWeight:"bold"}}>Go To Gestures</Text></TouchableOpacity>)} />
<ActualGesture/>
</View>
)
}
export default GestureScreen
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
circle:{
height:60,aspectRatio:1,backgroundColor:"blue",borderRadius:50
}
});
package.json
{
"name": "animate",
"version": "1.0.0",
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"eject": "expo eject"
},
"dependencies": {
"#react-navigation/native": "^6.0.8",
"#react-navigation/native-stack": "^6.5.0",
"expo": "~44.0.0",
"expo-status-bar": "~1.2.0",
"react": "17.0.1",
"react-dom": "17.0.1",
"react-native": "0.64.3",
"react-native-gesture-handler": "~2.1.0",
"react-native-reanimated": "~2.3.1",
"react-native-safe-area-context": "3.3.2",
"react-native-screens": "~3.10.1",
"react-native-web": "0.17.1"
},
"devDependencies": {
"#babel/core": "^7.12.9"
},
"private": true
}
From what i understand from the error is that the gesture function shouldve either been a JS thread or a worklet,i tried doing that to no avail by adding "worklet"; to the beginning of the functions code. Im guessing this is an android error, because based off youtube tutorials given an iOS emulator it works just fine. The gesture function is bringing the right coordinates, its just the changing of the styling to match the translatex value. Please help me i dont know how to carry on from here.
react-native-gesture-handler Gesture can run on js thread with .runOnJS(true) in your case it would be :
function ActualGesture() {
const translateX=useSharedValue(0);
// const translateY=useSharedValue(0);
const gesture=Gesture.Pan().runOnJS(true).onUpdate((event)=>{
translateX=event.translationX;
});
const rStyle=useAnimatedStyle(()=>{
return {
transform:[{translateX:translateX.value}],
};
});
return (
<GestureHandlerRootView style={styles.container}>
<GestureDetector gesture={gesture}>
<Animated.View style={[styles.circle,rStyle]}></Animated.View>
</GestureDetector>
</GestureHandlerRootView>
)
}
I'm learning reactNative and I cannot resolve an error. In the tutorial I'm following, we want to allow user to be able to add (or remove) movie to favourites and for that we are using Redux. After implementing the code when launch (through Expo Go on android), I've got the following error: undefined is not an object (evaluating 'store.getState'). Thanks
Reducers:
// Store/Reducers/favoriteReducer.js
const initialState = { favoritesFilm: [] }
function toggleFavorite(state = initialState, action) {
let nextState
switch (action.type) {
case 'TOGGLE_FAVORITE':
const favoriteFilmIndex = state.favoritesFilm.findIndex(item => item.id === action.value.id)
if (favoriteFilmIndex !== -1){
nextState = {
...state,
favoritesFilm: state.favoritesFilm.filter( (item, index) => index !== favoriteFilmIndex )
}
}
else{
nextState = {
...state,
favoritesFilm: [...state.favoritesFilm, action.value]
}
}
return nextState || state
default:
return state
}
}
export default toggleFavorite
Store configure:
// Store/configureStore.js
import { createStore } from 'redux';
import toggleFavorite from './Reducers/favoriteReducer'
export default createStore(toggleFavorite)
App.js
import React from 'react';
import Navigation from './Navigation/Navigation';
import { Provider } from 'react-redux';
import { Store } from './Store/configureStore';
export default class App extends React.Component {
render(){
return (
<Provider store={Store}>
<Navigation/>
</Provider>
)
}
}
Film detail
import React from 'react'
import { StyleSheet, View, Text, ActivityIndicator, ScrollView, Image } from 'react-native'
import { getFilmDetailFromApi, getImageFromApi } from '../API/TMDBApi'
import moment from 'moment'
import numeral from 'numeral'
import { connect } from 'react-redux';
class FilmDetail extends React.Component {
constructor(props) {
super(props)
this.state = {
film: undefined,
isLoading: true
}
}
componentDidMount() {
getFilmDetailFromApi(this.props.navigation.state.params.idFilm).then(data => {
this.setState({
film: data,
isLoading: false
})
})
}
_displayLoading() {
if (this.state.isLoading) {
return (
<View style={styles.loading_container}>
<ActivityIndicator size='large' />
</View>
)
}
}
_displayFilm() {
const { film } = this.state
if (film != undefined) {
return (
<ScrollView style={styles.scrollview_container}>
<Image
style={styles.image}
source={{uri: getImageFromApi(film.backdrop_path)}}
/>
<Text style={styles.title_text}>{film.title}</Text>
<Text style={styles.description_text}>{film.overview}</Text>
<Text style={styles.default_text}>Sorti le {moment(new Date(film.release_date)).format('DD/MM/YYYY')}</Text>
<Text style={styles.default_text}>Note : {film.vote_average} / 10</Text>
<Text style={styles.default_text}>Nombre de votes : {film.vote_count}</Text>
<Text style={styles.default_text}>Budget : {numeral(film.budget).format('0,0[.]00 $')}</Text>
<Text style={styles.default_text}>Genre(s) : {film.genres.map(function(genre){
return genre.name;
}).join(" / ")}
</Text>
<Text style={styles.default_text}>Companie(s) : {film.production_companies.map(function(company){
return company.name;
}).join(" / ")}
</Text>
</ScrollView>
)
}
}
render() {
console.log(this.props)
return (
<View style={styles.main_container}>
{this._displayLoading()}
{this._displayFilm()}
</View>
)
}
}
const styles = StyleSheet.create({
main_container: {
flex: 1
},
loading_container: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
alignItems: 'center',
justifyContent: 'center'
},
scrollview_container: {
flex: 1
},
image: {
height: 169,
margin: 5
},
title_text: {
fontWeight: 'bold',
fontSize: 35,
flex: 1,
flexWrap: 'wrap',
marginLeft: 5,
marginRight: 5,
marginTop: 10,
marginBottom: 10,
color: '#000000',
textAlign: 'center'
},
description_text: {
fontStyle: 'italic',
color: '#666666',
margin: 5,
marginBottom: 15
},
default_text: {
marginLeft: 5,
marginRight: 5,
marginTop: 5,
}
})
const mapStateToProps = (state) => {
return {
favoritesFilm: state.favoritesFilm
}
}
export default connect(mapStateToProps)(FilmDetail)
Package.json
{
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"eject": "expo eject"
},
"dependencies": {
"#react-native-community/masked-view": "^0.1.10",
"#react-navigation/native": "^5.9.3",
"#react-navigation/stack": "^5.14.3",
"expo": "~40.0.0",
"expo-status-bar": "~1.0.3",
"moment": "^2.29.1",
"numeral": "^2.0.6",
"react": "16.13.1",
"react-dom": "16.13.1",
"react-native": "https://github.com/expo/react-native/archive/sdk-40.0.1.tar.gz",
"react-native-gesture-handler": "~1.8.0",
"react-native-reanimated": "~1.13.0",
"react-native-safe-area-context": "^3.1.9",
"react-native-screens": "~2.15.2",
"react-native-web": "~0.13.12",
"react-navigation": "^4.4.4",
"react-navigation-stack": "^2.10.4",
"react-redux": "^7.2.2",
"redux": "^4.0.5"
},
"devDependencies": {
"#babel/core": "~7.9.0",
"typescript": "~4.0.0",
"#types/react": "~16.9.35",
"#types/react-native": "~0.63.2"
},
"private": true
}
UPDATE: changing import { Store } from './Store/configureStore'; to import Store from './Store/configureStore'; in App.js makes it work
Already answer here: TypeError: undefined is not an object (evaluating 'store.getState')
you have to change
Store config:
export const store = createStore(toggleFavorite)
now you can import like this
import { store } from './Store/configureStore';
In mapStateToProps add (toggleFavorite) reducer where, that (favoritesFilm) state is present
const mapStateToProps = (state) => {
return {
favoritesFilm: state.toggleFavorite.favoritesFilm
}
}
I am developing news app using react native, and my problem is the launch or startup time of app is long(before the home screen shows), I would appreciate any advice to improve the speed.It takes around 4 seconds to load initially and 2 seconds for the js. I have 36 articles to show on home screen and the json response is big and maybe it is the reason of the problem.
My package.json looks like this :
{
"name": "tageblattapp",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"#react-native-community/masked-view": "^0.1.7",
"moment": "^2.24.0",
"native-base": "^2.13.12",
"react": "16.11.0",
"react-native": "0.62.0",
"react-native-gesture-handler": "^1.6.1",
"react-native-optimized-flatlist": "^1.0.4",
"react-native-reanimated": "^1.7.1",
"react-native-render-html": "^4.2.0",
"react-native-safe-area-context": "^0.7.3",
"react-native-safe-area-view": "^1.0.0",
"react-native-screens": "^2.7.0",
"react-native-vector-icons": "^6.6.0",
"react-native-webview": "^9.3.0",
"react-navigation": "^4.3.5",
"react-navigation-drawer": "^2.4.12",
"react-navigation-stack": "^2.3.9"
},
"devDependencies": {
"#babel/core": "7.9.0",
"#babel/runtime": "7.9.2",
"#react-native-community/eslint-config": "0.0.5",
"babel-jest": "24.9.0",
"eslint": "6.8.0",
"jest": "24.9.0",
"metro-react-native-babel-preset": "0.58.0",
"react-test-renderer": "16.11.0"
},
"jest": {
"preset": "react-native"
},
"rnpm": {
"assets": [
"../assets/fonts/"
]
}
}
My imports are:
import React,{PureComponent} from 'react';
import {AsyncStorage, Linking ,Share, View ,Image,ActivityIndicator ,StyleSheet, TouchableOpacity,Dimensions,ScrollView,SafeAreaView, TextInput ,FlatList} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import { createAppContainer } from 'react-navigation';
import {Container, Header, Left, Body, Right, Button, Title,Text,Content, List, ListItem,Thumbnail} from 'native-base';
import { createStackNavigator } from 'react-navigation-stack';
import { createDrawerNavigator } from 'react-navigation-drawer';
import { IMAGE } from '../constants/image';
import { getMenusideGategory} from '../services/news';
import HTML from 'react-native-render-html';
import Time from '../components/time';
import moment from 'moment';
import FeedDetail from './FeedDetail';
import ArticleLink from './ArticleLink';
import Comments from './Comments';
import AddComments from './AddComments';
The funcyion that gets articles:
export async function getArticles(){
try {
let articles = await fetch(`${articles_url}`,{
headers:{
'X-API-KEY':_api_key
}
});
let result = await articles.json();
return result.articles;
} catch (error) {
throw error
}
}
The home.js that display the articles is :
export class HomeScreen extends PureComponent {
constructor(props) {
super(props);
this._handleItemDataOnPress = this._handleItemDataOnPress.bind(this)
this.state = {
isLoading: true,
data: null,
isError: false,
setModalVisible: false,
modalArticleData: {}
}
}
_handleItemDataOnPress(articleData) {
this.setState({
setModalVisible: true,
modalArticleData: articleData
})
}
componentDidMount() {
getArticles().then(data => {
this.setState({
isLoading: false,
data: data
})
}, error => {
Alert.alert("Error", "Something happend, please try again")
})
}
render() {
let view = this.state.isLoading ? (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<ActivityIndicator animating={this.state.isLoading} color="#00f0ff" />
<Text style={{ marginTop: 8 }} children="Please wait..." />
</View>
) : (
<FlatList
dataArray={this.state.data}
renderRow={(item) => {
return (
<ListItem>
<ListDataItem onPress={this._handleItemDataOnPress} data={item} />
</ListItem>
)
}} />
)
return (
<Container>
<Header>
<Body>
<Title children="RN NewsApp" />
</Body>
</Header>
<Content
contentContainerStyle={{ flex: 1, backgroundColor: '#fff' }}
padder={false}>
{view}
</Content>
</Container>
)
}
}
The class ListDataItem that shows single data item inside the list renderRow:
export default class ListDataItem extends PureComponent{
constructor(props){
super(props);
this.data = props.data;
this._handlePress = this._handlePress.bind(this)
}
_handlePress(){
const {url, title} = this.data
this.props.onPress({url,title})
}
render(){
return(
<TouchableOpacity onPress={this._handlePress} style={{flexDirection:'row'}} activeOpacity={0.5}>
<Thumbnail style={{ backgroundColor: '#eee', alignSelf: 'center' }} square large source={{ cache:'force-cache', uri: this.data.urlToImage != null ? this.data.urlToImage : null }} />
<Body>
<Text style={{fontSize: 16 }} numberOfLines={2}>{this.data.title}</Text>
<Text note numberOfLines={3}>{this.data.description}</Text>
<View style={{ flex: 1, flexDirection: 'row', marginTop: 8, marginLeft: 8 }}>
<Text note>{this.data.source.name}</Text>
<TimeAgo date={this.data.publishedAt} />
</View>
</Body>
</TouchableOpacity>
)
}
}
I tried also to put the header inside the flatlist using LisHeaderComponent, but there was no difference.
Decrease your start up time and RAM memory consumption by an application via splitting JS bundle by components and navigation routes.
https://www.npmjs.com/package/react-native-bundle-splitter
Just by creating a release Apk/Build
In a release Apk, App loads in just half a second which means the Splash screen or Launch screen shows up for half a second only.
I am doing doing navigation with new react native navigation all I want is when button is pressed it navigate to next screen, I have followed new documentation but the problem is I am doing with classes and in the documentation all the work is done with functions in App.js, I tried to modify my code accordingly but couldn't do with classes as onPress button it does not navigate instead gives me error.
This is my app.js:
import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer,useNavigation } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import Nav from './screens/Nav';
import Home from './screens/Home';
import Login from './screens/Login';
const Stack = createStackNavigator();
export default class App extends React.Component {
render(){
return (
<NavigationContainer>
<Stack.Navigator headerMode='none' initialRouteName="Nav">
<Stack.Screen name="Splash" component={Nav} />
<Stack.Screen name="Home" component={Home} />
<Stack.Screen name="Login" component={Login} />
</Stack.Navigator>
</NavigationContainer>
);
}
}
That is my Home.js from where when it clicks Login button it moves to next screen which is Login.js:
import React, { Component } from 'react';
import {StyleSheet, Text, View, TouchableHighlight,Image,BackHandler} from 'react-native';
import Login from './Login';
export default class Home extends Component {
render() {
const { navigation } = this.props;
return (
<View style={styles.container}>
<TouchableHighlight style={styles.buttonContainer} onPress={() => navigation.navigate('Login')}>
<Text style={styles.loginText}>Login</Text>
</TouchableHighlight>
</View>
);
}
}
That is my Login.js Screen:
import React, { Component } from 'react';
import {StyleSheet, Text, View,TextInput,TouchableHighlight, Image} from 'react-native';
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
email : '',
password: '',
}
}
render() {
return (
<View style={styles.container}>
<Image source={require('../assets/logo.png')}
style={{ width: 250, height: 250, marginHorizontal: 20 }}
resizeMode="contain"/>
<Text style = {styles.text}>UniQmove Training </Text>
<View style={styles.inputContainer}>
<Image style={styles.inputIcon} source={{uri: 'https://img.icons8.com/ultraviolet/40/000000/email.png'}}/>
<TextInput style={styles.inputs}
placeholder="Email"
keyboardType="email-address"
underlineColorAndroid='transparent'
onChangeText={(email) => this.setState({email})}/>
</View>
<View style={styles.inputContainer}>
<Image style={styles.inputIcon} source={{uri: 'https://img.icons8.com/ultraviolet/40/000000/password.png'}}/>
<TextInput style={styles.inputs}
placeholder="Password"
secureTextEntry={true}
underlineColorAndroid='transparent'
onChangeText={(password) => this.setState({password})}/>
</View>
<TouchableHighlight style={[styles.buttonContainer, styles.loginButton]} onPress={() => {this.loginRoles();this.handleLogin();}}>
<Text style={styles.loginText}>Login</Text>
</TouchableHighlight>
</View>
);
}
}
The problem is when I import Login.js in Home it is not using it in navigation.navigate('Login')
My package.jason:
{
"name": "UniQmoves",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"#react-native-community/masked-view": "^0.1.7",
"#react-navigation/native": "^5.0.9",
"#react-navigation/stack": "^5.1.1",
"react": "16.9.0",
"react-native": "0.61.5",
"react-native-gesture-handler": "^1.6.0",
"react-native-reanimated": "^1.7.0",
"react-native-safe-area-context": "^0.7.3",
"react-native-screens": "^2.3.0"
},
"devDependencies": {
"#babel/core": "7.8.7",
"#babel/runtime": "7.8.7",
"#react-native-community/eslint-config": "0.0.5",
"babel-jest": "24.9.0",
"eslint": "6.8.0",
"jest": "24.9.0",
"metro-react-native-babel-preset": "0.56.4",
"react-test-renderer": "16.9.0"
},
"jest": {
"preset": "react-native"
}
}
there is a little change in code and your code will work fine
in App Class initialRouteName and screen name should same change Splash to Nav
<Stack.Navigator headerMode='none' initialRouteName="Nav">
<Stack.Screen name="Splash" component={Nav} />
in Home class update after use this line
import React, { Component } from 'react';
import {StyleSheet, Text, View, TouchableHighlight,Image,BackHandler} from 'react-native';
import Login from './Login';
export default class Home extends Component {
render() {
return (
<View style={styles.container}>
//<TouchableHighlight style={styles.buttonContainer} onPress={() => navigation.navigate('Login')}>
use this
<TouchableHighlight style={styles.buttonContainer} onPress={() => this.props.navigation.navigate('Login')}>
<Text style={styles.loginText}>Login</Text>
</TouchableHighlight>
</View>
);
}
}
I have deleted node_modules and rerun npm install. After that i got this error:
Error while updating property 'fontSize' in shadow node of type: RCTText
Value for fontSize cannot be cast from String to Double
I change all fontSize in form of fontSize:'20' to fontSize:20 but the error showing again. Now I removed fontSize property in all files and again error exist.
here is my package.json content:
{
"name": "myApp",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"jetifier": "^1.6.4",
"native-base": "^2.13.8",
"prop-types": "^15.7.2",
"react": "16.8.3",
"react-native": "0.59.8",
"react-native-dialog": "^5.6.0",
"react-native-gesture-handler": "^1.5.0",
"react-native-ionicons": "^4.6.3",
"react-native-material-dropdown": "^0.11.1",
"react-native-responsive-screen": "^1.3.0",
"react-native-slideshow": "^1.0.1",
"react-navigation": "^3.13.0"
},
"devDependencies": {
"#babel/core": "7.4.4",
"#babel/runtime": "7.4.4",
"babel-jest": "24.8.0",
"jest": "24.8.0",
"metro-react-native-babel-preset": "0.54.0",
"react-test-renderer": "16.8.3"
},
"jest": {
"preset": "react-native"
},
"rnpm": {
"assets": [
"./assets/fonts"
]
}
}
UPDATE:
MainPage of the app:
import React, { Component } from 'react';
import { View, Text,StyleSheet,Image,TouchableWithoutFeedback } from 'react-native';
import Slideshow from 'react-native-slideshow';
import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen';
import Colors from '../Colors';
import Strings from '../Strings';
import DrawerNavigator from '../routes/DrawerNavigator';
class AppMainPage extends Component {
constructor(props) {
super(props);
this.state = {
position: 0,
interval: null,
dataSource: [],
sliderSource:[]
};
}
componentDidMount(){
this.fetchSliderImage();
}
componentWillMount() {
this.setState({
interval: setInterval(() => {
this.setState({
position: this.state.position === this.state.dataSource.length-1 ? 0 : this.state.position + 1
});
}, 2000)
});
}
componentWillUnmount() {
clearInterval(this.state.interval);
}
getAuthAndReload(){
ajax.fetchAuth().then(()=>{this.fetchSliderImage()});
}
async fetchSliderImage(){
try{
let response = await fetch(Strings.baseUrl+'spanser/new?type=1&ostanId=1', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' +Strings.id_token
}
}).then((resp) => {
return resp.json()
})
.then((responseJson) => {
const json_data = responseJson;
if("title" in responseJson && responseJson.title=="Unauthorized" ){
this.setState({loadData:1},()=>this.getAuthAndReload());
return 0;
}
else{
const arr = Object.keys(json_data).map(function(_) { return json_data[_]; });
var resultArray=new Array();
for(i=0;i<arr.length;i++){
resultArray.push({'title':arr[i].title,'caption':'','url':Strings.imageUrl+arr[i].image1});
}
this.setState({sliderSource:resultArray,dataSource:arr});
return arr;
}
});
}
catch (error) {
console.error(error);
}
}
onImageClick(){
console.log('&&'+this.state.dataSource[0]);
console.log('******'+this.state.position);
this.props.navigation.navigate('SponserPage',{currentItem:this.state.dataSource[this.state.position]})
}
render() {
return (
<View style={{backgroundColor:'black',flex:1}}>
<DrawerNavigator/>
<View style={styles.rowViews}>
<View style={styles.columnViews}>
<Image style={styles.imgStyle} source={require('../Icons/play-button.png')}/>
<Text style={styles.txtStyle}>ویدیوی ویژه</Text>
</View>
<View style={styles.columnViews}>
<Image style={styles.imgStyle} source={require('../Icons/star.png')}/>
<Text style={styles.txtStyle}>پیشنهادهای ویژه</Text>
</View>
<View style={styles.columnViews}>
<Image style={styles.imgStyle} source={require('../Icons/irandokht.png')}/>
<TouchableWithoutFeedback onPress={()=>this.props.navigation.navigate('SalonList')}>
<Text style={styles.txtStyle}>لیست سالنها</Text></TouchableWithoutFeedback>
</View>
</View>
<View style={{width:'100%',height:2,backgroundColor:Colors.yellow}}/>
<View style={styles.rowViews}>
<View style={styles.columnViews}>
<Image style={styles.imgStyle} source={require('../Icons/trophy.png')}/>
<Text style={styles.txtStyle}>برندگان مسابقات</Text>
</View>
<View style={styles.columnViews}>
<Image style={styles.imgStyle} source={require('../Icons/trophy(1).png')}/>
<Text style={styles.txtStyle}>سالن برتر ماه</Text>
</View>
<TouchableWithoutFeedback style={styles.columnViews} onPress={()=>this.props.navigation.navigate('Mosabeqat')}>
<View >
<Image style={styles.imgStyle} source={require('../Icons/medal.png')}/>
<Text style={styles.txtStyle}>شرکت در مسابقه </Text>
</View>
</TouchableWithoutFeedback>
</View>
<View style={styles.rowViews}>
<View style={styles.columnViews}>
<Image style={styles.imgStyle} source={require('../Icons/contact.png')}/>
<Text style={styles.txtStyle}>ارتباط با ایران دخت</Text>
</View>
<TouchableWithoutFeedback style={styles.columnViews} onPress={()=>this.props.navigation.navigate('MajaleyeTakhasosi')}>
<View >
<Image style={styles.imgStyle} source={require('../Icons/open-magazine.png')}/>
<Text style={styles.txtStyle}>مجله تخصصی</Text>
</View>
</TouchableWithoutFeedback>
<View >
<Image style={styles.imgStyle} source={require('../Icons/newspaper.png')}/>
<TouchableWithoutFeedback style={styles.columnViews} onPress={()=>this.props.navigation.navigate('NewsNav')}>
<Text style={styles.txtStyle}>اخبار مهم</Text>
</TouchableWithoutFeedback></View>
</View>
<View style={styles.columnViews}>
{this.state.sliderSource.length>0?
<Slideshow
containerStyle={{padding: 10,}}
dataSource={this.state.sliderSource}
position={this.state.position}
resizeMode='contain'
onPositionChanged={position => this.setState({ position:position })}
onPress={()=>{this.onImageClick()}}/>
:
<View/>
}
</View>
</View>
);
}
}
const styles=StyleSheet.create(
{
rowViews:{
flexDirection:'row',
justifyContent: 'space-between',
alignItems: 'center',
margin:10,
flex:1
},
columnViews:{
flexDirection:'column',
justifyContent: 'center',
alignItems: 'center',
margin: 5,
},
txtStyle:{
fontFamily: 'BYEKAN',
color:'white'
},
imgStyle:{
height:hp('20%'),
width:wp('20%'),
resizeMode:'contain'
}
}
)
export default AppMainPage;
I don't know how to fix error. thanks for any help
these are photo of error:
this can be solved be using:
fontSize: 20
instead of:
fontSize: "20px"
or
fontSize: '20px'
..apparently its expecting a number and not a string. PS, string works well on the iOS device but gives error on the Android device.
If you have a package.lock file or yarn.lock, delete it, delete the node_modules folder and run
npm cache clean --force
then run:
npm install or yarn install
Somewhere you are changing your fontSize from string to double it could be text as well icons if you are using icons somewhere,
I was having the same issue solved giving equivalent datatype to every where i'm using font or icons
react-native link.
I have deleted the previous line of code where I got this error and ran server again add the code and run server.
By this issue resolved for me.
I had the same problem, but I discovered that I should use only double quotes "" Always use Double in your style.
const styles=StyleSheet.create(
{
rowViews:{
flexDirection:"row",
justifyContent: "space-between",
alignItems: "center",
margin:10,
flex:1
},
columnViews:{
flexDirection:"column",
justifyContent: "center",
alignItems: "center",
margin: 5,
},
txtStyle:{
fontFamily: "BYEKAN",
color:"white"
},
imgStyle:{
height:hp("20%"),
width:wp("20%"),
resizeMode:"contain"
}
}
)
It takes number not string
ex. fontSize:19,