我在渲染组件之前从我的 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
,告诉是否已从服务器检索到任务。如果没有,那么你渲染一条消息,说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
状态,并且至少有一个可以在屏幕上呈现的任务。