[英]How to properly update a react native swiper component when state changes?
我有一個使用react-native-swiper
模塊的react本機組件。 swiper中的一個幻燈片包含在組件狀態中設置的文本。 在組件中,我還有一個帶有窗體的模態,當用戶嘗試從模態中保存輸入數據時,該窗體會更改狀態的文本。
問題是:在我當前的實現中,每次我保存新數據時,swiper都會被拖動到最后一張幻燈片,並重新渲染幻燈片(過程是滯后的)。 所以我想知道更順暢更新幻燈片的最佳方法是什么?
以下是我的組件:
'use strict';
import React from 'react';
import {
Dimensions,
StyleSheet,
View,
Text,
ScrollView,
AlertIOS,
AsyncStorage
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import Swiper from 'react-native-swiper';
import Button from 'react-native-button';
import { saveName, getName } from '../Utils/dataService';
import { showAlert } from '../Utils/alert';
import HeaderSection from './HeaderSection';
import { styles } from '../Styles/Styles';
import { renderPagination } from './renderPagination';
class MainView extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
currIndex: 0
};
}
componentDidMount() {
getName(val => this.setState({'name': val}));
}
showInputModal() {
AlertIOS.prompt(
'Enter New Doctor Name', null,
[
{
text: 'Save',
onPress: name => saveName(name, val => this.setState({'name': val}))
},
{ text: 'Cancel', style: 'cancel' }
]
);
}
render() {
return (
<View style={{flex: 1}}>
<Swiper ref='swiper' onIndexChanged={(index) => this.setState({'currIndex': index})}>
<View style={styles.slide}>
<Text style={styles.text}>Hello {this.state.name}</Text>
</View>
</Swiper>
<Button onPress={this.showInputModal.bind(this)}>
Customize
</Button>
</View>
);
}
}
export default MainView;
我有類似的問題。 然后我嘗試從狀態渲染Swiper
(在你的情況下)並優化性能。 我希望它也能解決你的問題。
只需用以下內容替換您的class MainView
:
class MainView extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
currIndex: 0,
swiper: this.renderSwpier
};
}
componentDidMount() {
getName(val => this.setState({'name': val}));
}
renderSwpier(){
return(
<Swiper ref='swiper' onIndexChanged={(index) => this.setState({'currIndex': index})}>
<View style={styles.slide}>
<Text style={styles.text}>Hello {this.state.name}</Text>
</View>
</Swiper>
)
}
showInputModal() {
AlertIOS.prompt(
'Enter New Doctor Name', null,
[
{
text: 'Save',
onPress: name => saveName(name, val => this.setState({'name': val}))
},
{ text: 'Cancel', style: 'cancel' }
]
);
}
render() {
return (
<View style={{flex: 1}}>
{this.state.swiper.call(this)}
<Button onPress={this.showInputModal.bind(this)}>
Customize
</Button>
</View>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.