TypeError: Невозможно прочитать свойство 'events' из null при попытке получить доступ к состоянию в React Native - PullRequest
0 голосов
/ 08 января 2019

Я получаю сообщение об ошибке ниже в приложении, которое создаю.

TypeError: TypeError: Cannot read property 'events' of null

Я пытаюсь получить «события» из хранилища с помощью AsyncStorage и назначить его событиям переменной состояния в жизненном цикле ComponentDidMount.

Я думаю, что состояние не обновляется до визуализации компонента приложения! Но я не знаю, как решить эту проблему на данный момент.

Любая помощь будет принята с благодарностью!

import backgroundImage from '../assets/bg.jpg';
import OhButton from '../components/Buttons/OhButton';
import H1 from '../components/Headings/H1';
import Heading from '../components/TextWraps/Heading';


class Home extends Component{

  constructor(props) {
    super(props);

    state = {
      events: ''
    }
  }

  componentDidMount(){
    this.getDataFromStorage('Test');
  }

  async getDataFromStorage(key){
    let events = await AsyncStorage.getItem(key).then((res) => {
      this.setState({ events: res });
    });
  }


  render() {
    const noEventsFound = (
      <View>
        <Heading>
          <H1>No Events Found!</H1>
        </Heading>
        <OhButton color="#7BE78A" onPress={() => this.props.navigation.navigate('Register')}>CREATE AN EVENT</OhButton>
      </View>
    );

    const thereAreEvents = (
      <View>
        <Heading>
          <H1>There are Events!</H1>
        </Heading>

      </View>
    );

    return (
      <ImageBackground source={backgroundImage} style={styles.backgroundImage}>
        <View style={styles.container}>
          {noEventsFound}
        </View>
      </ImageBackground>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 10,
  },
  backgroundImage:{
    width: "100%",
    flex: 1
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  textHeading:{
    fontSize: 28,
    fontWeight: "bold"
  },
});

const mapStateToProps = state => {
  return {
    eventsA : state.eventsR.events
  }
};

const mapDispatchToProps = dispatch => {
  return {
    loadEvents: () => dispatch(loadEvents())
  }
};

export default connect(mapStateToProps,mapDispatchToProps)(Home);

1 Ответ

0 голосов
/ 08 января 2019

вы должны импортировать AsyncStorage

import { AsyncStorage } from 'react-native'
...