machadogj / react-native-carousel-control

React Native Carousel control with support for iOS and Android
MIT License
247 stars 55 forks source link

changing parent component state within onPageChange prop results in undesired behavior #29

Open kaloncheung124 opened 7 years ago

kaloncheung124 commented 7 years ago

In my app, we have a screen component that contains the carousel and a list of data. We wish to use the carousel onPageHandler to select between different sources for the data. However, when we try to change the screen component state within onPageChange, the carousel pauses and then scrolls back to the first element.

Here is the stripped down code for our home screen with the carousel within it:

export default class HomeScreen extends React.component {

    constructor(props) {
        super(props);
        this.state = {currPageNum: 0};
    }

    ...

    render() {
        return (
            <View>
                <Carousel
                    initialPage={0}
                    pageStyle={{
                        flex: 1,
                        flexDirection: 'column',
                        alignItems: 'center',
                        justifyContent: 'flex-start',
                        padding: 5,
                        backgroundColor: '#f7f7f7',
                    }}
                    sneak={0}
                    swipeThreshold={0.25}
                    onPageChange={(page) => {
                        console.log(page);
                        this.setState({currPageNum: page})
                     }}
                >
                    {...}
                </Carousel>
            </View>
        );
    }

Any help would be greatly appreciated!

kaloncheung124 commented 7 years ago

I think it's due to the currentPage default prop. If I haven't set the currentPage prop, whenever componentWillReceiveProps gets called, it still receives a currentPage prop with a value of 0. This sets this.state.currentPage to 0 whenever the carousel is re-rendered. Perhaps remove this from the default props and add some checking for undefined?