[英]React-Native/Redux - Unable to fetch data before component mounts
我在從Web服務中獲取數據並在呈現組件之前更新this.props
遇到問題。
Homepage.js
import React, { Component } from 'react';
import {View, Text, StyleSheet, Image} from 'react-native';
import { Header, Footer , CarouselSlide} from './common';
import { connect } from 'react-redux';
import { getQuests} from '../actions';
import Carousel from 'react-native-snap-carousel';
const SLIDER_1_FIRST_ITEM = 1;
class HomePage extends Component {
constructor (props) {
super(props);
this.state = {
slider1ActiveSlide: SLIDER_1_FIRST_ITEM,
slider1Ref: null
};
}
componentWillMount() {
this.props.getAllQuests();
}
_renderItemWithParallax({item, index}, parallaxProps) {
return(
<CarouselSlide
data={item}
parallaxProps={parallaxProps}
/>
);
}
render() {
const {containerStyle, questHeaderStyle, questHeaderTextStyle} = styles;
const {slider1ActiveSlide, slider1Ref} = this.state;
return(
<View style={containerStyle}>
<Header />
<View style={questHeaderStyle}>
<Text style={questHeaderTextStyle}>Quests</Text>
</View>
<Carousel
ref={(c) => { if (!this.state.slider1Ref) { this.setState({ slider1Ref: c}); } }}
data={this.props.questObject}
renderItem={this._renderItemWithParallax}
sliderWidth={300}
itemWidth={300}
hasParallaxImages={true}
firstItem={1}
inactiveSlideScale={0.94}
inactiveSlideOpacity={0.7}
enableMomentum={false}
loop={true}
loopClonesPerSide={2}
autoplay={true}
autoplayDelay={500}
autoplayInterval={3000}
onSnapToItem={(index) => this.setState({ slider1ActiveSlide: index})}
/>
<Footer />
</View>
);
}
}
const styles = StyleSheet.create({
containerStyle: {
flex: 1
},
questHeaderStyle: {
left: 17.5,
top: 5
},
questHeaderTextStyle: {
color: '#EF6D69',
fontSize: 17.5,
fontWeight: '800'
}
})
const mapStateToProps = ({quest}) => {
const { error, loading, questObject } = quest;
return { error, loading, questObject};
};
const mapDispatchToProps = (dispatch) => {
return {
getAllQuests: () => {
dispatch(getQuests());
}
};
};
export default connect(mapStateToProps, mapDispatchToProps)(HomePage);
似乎僅在組件渲染后才分派動作,如何在組件安裝前分派動作?
由於您是從Web服務中獲取數據,因此可能要花費未知的時間,並且要等到那個時候才能保留組件的呈現。 您需要在此處保持一個state
,該state
告訴您是否已從服務器檢索到任務。 如果不是,則渲染一條消息,提示Fetching quests
或其他內容,一旦有要渲染的任務,便開始渲染這些任務。 偽代碼想要類似
class HomePage extends Component {
state = {
hasSomeQuests: false
}
updateHasSomeQuestsToRender = (newValue) => {
this.setState({
hasSomeQuests: newValue
})
}
render() {
if(!this.state.hasSomeQuests) {
return <Fetching quests>
}
return JSX with the quests
}
}
當您檢索任務並具有至少一個可以在屏幕上呈現的任務時,可以更新hasSomeQuests
狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.