我正在构建的某个应用程序出现以下错误。
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);
答案 0 :(得分:0)
您必须导入AsyncStorage
import { AsyncStorage } from 'react-native'