Я использую реагировать нативно для создания мобильного приложения.Я пытаюсь подключить компонент к магазину, чтобы получить начальное глобальное состояние в этом компоненте.Моя проблема в том, что я получаю неопределенное значение.Мой магазин:
import { createStore, applyMiddleware } from "redux"
import { composeWithDevTools } from "redux-devtools-extension"
import thunk from "redux-thunk"
import reducers from "./reducers"
const composedEnhancer = composeWithDevTools(applyMiddleware(thunk))
const store = createStore(reducers, {}, composedEnhancer)
export default store;
Мое начальное состояние в магазине:
export default initialState = {
token: null,
isVisible: true,
WhoIs: "Apporteur d'affaires Immobilier",
};
Мой редуктор:
import {
AUTH_SET_TOKEN,
AUTH_REMOVE_TOKEN,
AUTH_GET_TOKEN,
SET_USER_TYPE
}
from "./types";
import initialState from './initialState';
const reducers = (state = initialState, action) => {
switch (action.type) {
case AUTH_SET_TOKEN:
return {
...state,
token: action.value,
};
case AUTH_REMOVE_TOKEN:
return {
...state,
token: null,
};
case SET_USER_TYPE:
return {
...state,
WhoIs: action.value
}
default:
return state;
}
};
export default reducers;
Я пытаюсь подключитькомпонент для редукции следующим образом:
const mapStateToProps = state => ({
token: state.token,
isVisible: state.isVisible,
WhoIs: state.WhoIs,
})
export default connect(mapStateToProps)(FirstStep);
Глобальная переменная WhoIs в состоянии получает «Apporteur d'affaires Immobilier» в качестве начального значения, но когда я вызываю эту глобальную переменную в моем компоненте, используя mapStateToProps, я получаю неопределенное значение.Я использовал: console.log(this.props)
, чтобы показать реквизиты компонента.Поставщик:
render() {
const Root = () => {
if (!this.state.isReady) {
return (
<AppLoading
startAsync={this._loadAssetsAsync}
onFinish={() => this.setState({ isReady: true })}
/>
)
}
return <AppContainer />;
}
return (
<Provider store={store}>
<Root />
</Provider>
);
}
}
export default App;
Компонент FirstStep:
/**
* eXpand Mobile App
* React Native
* Propriétés Privées 2019
*/
import React, { Component } from 'react';
import { connect } from 'react-redux';
import store from "../../../Store/store";
/**
* React Native
*/
import {
View,
Text,
ScrollView,
StyleSheet,
Platform,
Image,
ActivityIndicator,
SafeAreaView,
Alert,
AsyncStorage
}
from 'react-native';
// import Icon from 'react-native-vector-icons/MaterialIcons';
// import Icon from 'react-native-vector-icons/FontAwesome';
/**
* React Native Elements
*/
import {
Icon,
} from 'react-native-elements';
/**
* Get API DATA
*/
import API from '../../Api/global';
import axios from 'axios';
class FirstStep extends Component {
constructor(props) {
super(props);
this.state = {
Background: null,
// WhoIs: null
}
}
_getThemeForCurrentUser(value) {
if (value == "Negociateur") {
return "#0C6296"
} else {
return "#BDE9ED"
}
}
_UpdateBackground() {
this.setState({
Background: this._getThemeForCurrentUser(value)
})
}
/**
* ASYNC FUNCTION TO SAVE ITEM TO DEVICE STORAGE
*/
_storeData = async (item, selectedValue) => {
try {
await AsyncStorage.setItem(item, selectedValue);
} catch (error) {
console.error('AsyncStorage error: ' + error.message);
}
};
/**
* ASYNC FUNCTION TO GET ITEM FROM DEVICE STORAGE
*/
_retrieveData = async (item) => {
try {
const value = await AsyncStorage.getItem(item);
if (value !== null) {
Alert.alert(value);
console.log(value);
}
} catch (error) {
Alert.alert(error);
}
};
/**
* CLEAR ASYNC STORAGE : DELETE ALL DATA
*/
_clearAsyncStorage = async () => {
AsyncStorage.clear();
}
componentDidMount() {
}
showAlert() {
// Works on both iOS and Android
Alert.alert(
"Ne Plus Afficher ce contenu",
"Ce tutoriel ne sera plus affiché au démarrage de l'application",
[
{
text: 'Annuler',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{
text: 'Confirmer', onPress: () => {
this._storeData('isVisible', 'false'),
this.props.navigation.navigate('Dashboard')
}
},
],
{ cancelable: false },
);
}
render() {
const { navigate } = this.props.navigation;
console.log("####################")
console.log(this.props)
console.log("####################")
return (
<View style={{
flex: 1
}}>
<SafeAreaView style={{
paddingTop: Platform.OS === 'android' ? 25 : 0,
backgroundColor: 'rgba(82, 159, 197, 1)'
}}>
</SafeAreaView>
<View style={{
flex: 1,
flexDirection: 'row',
justifyContent: 'flex-end',
alignContent: 'center',
alignItems: 'center'
}}>
<Icon
reverse
name='close'
type='font-awesome'
color='#517fa4'
containerStyle={{ opacity: 0.8 }}
onPress={() => this.showAlert()}
/>
</View>
<View style={{
flex: 4,
justifyContent: 'center',
alignContent: 'center',
alignItems: 'center'
}}>
<Image
source={require('../../../assets/Backgrounds/Grey-Background.jpg')}
style={{ height: 200 }}
resizeMode="contain"
/>
</View>
<View style={{
flex: 4,
justifyContent: 'flex-start',
alignContent: 'center',
alignItems: 'center'
}}>
<Text style={styles.heading}> Développez votre réseau </Text>
<Text style={styles.subHeading}> facilement </Text>
</View>
<View style={{
flex: 1,
flexDirection: 'row',
justifyContent: 'flex-start'
}}>
<Icon
reverse
name='forward'
type='font-awesome'
color='#517fa4'
containerStyle={{ opacity: 0.8 }}
onPress={() => navigate('SecondStep')}
/>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
heading: {
color: 'black',
fontSize: 22,
alignContent: 'center',
fontFamily: 'SFUIDisplayBlack'
},
subHeading: {
color: 'black',
marginTop: 10,
fontSize: 22,
alignContent: 'center',
fontFamily: 'SFUIDisplayBlack'
},
titleText: {
fontSize: 25,
fontWeight: 'bold',
textAlign: 'center',
paddingVertical: 5,
fontFamily: Platform.OS === 'ios' ? 'SFUIDisplayBlack' : null,
color: '#27ae60',
},
subtitleText: {
fontSize: 18,
fontWeight: '400',
textAlign: 'center',
fontFamily: Platform.OS === 'ios' ? 'SFUIDisplayBlack' : null,
color: '#34495e',
},
});
/**
* Here the state is the value of store.getState()
* mapStateToProps argument is the entire redux store state
* we can called state or store or any variable
*/
const mapStateToProps = state => ({
token: state.token,
isVisible: state.isVisible,
WhoIs: state.WhoIs,
})
export default connect(mapStateToProps)(FirstStep);
Как правильно получить доступ к начальному состоянию магазина.