Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-redux connect passes props too late

I am writing simple audio player using react-native. And i have got an issue about passing props to component across react-redux connect method.

Here is my Container code:

import { connect } from 'react-redux';

import Music from './Music';
import MusicActions from '../../Actions/MusicActions';

const mapStateToProps = store => ({
  tracksObject: store.MusicReducer.get('tracks'),
  isLoaded: store.MusicReducer.get('isLoaded'),
  isLoading: store.MusicReducer.get('isLoading'),
  playing: store.MusicReducer.get('playing'),
  duration: store.MusicReducer.get('duration'),
});

const mapDispatchToProps = dispatch => ({
  movePan: value => dispatch(MusicActions.movePan(value)),
});

export default connect(mapStateToProps, mapDispatchToProps)(Music);

And here is few methods from component

  componentWillReceiveProps() {
    if (this.props.playing) {
      const step = this.props.duration * 0.025;
      const stepFrequency = this.props.duration / step;
      const intervalID = setInterval(
        () => this.setState(state => ({ sliderValue: 
(state.sliderValue + step) })),
    stepFrequency,
      );

      this.setState({ intervalID });
    }
  }

  render() {
    return (
      <View style={styles.view}>
        <View>
          { this.renderSongList() }
       </View>
       <Slider
          value={this.state.sliderValue}
          onValueChange={(value) => { this.onSliderChange(value); }}
          style={styles.slider}
          minimumTrackTintColor="#ba383a"
          thumbStyle={{ top: 22, backgroundColor: '#ba383a' }}
       />
      </View>
   ); 
 }

When song loads and stores value 'playing' becomes true, components method componentWillReceiveProps calls, but this.props.playing flag is false in spite of it is true in mapStateToProps. But after componentWillReceiveProps render calls and this.props.playing is true there.

like image 281
Vitali Skripka Avatar asked May 26 '17 11:05

Vitali Skripka


1 Answers

This is expected behavior, in componentWillReceiveProps, this.props is a reference to the previous props. You'll want to use the nextProps parameter of componentWillRecieveProps.

componentWillReceiveProps(nextProps) {
  if (nextProps.playing) {
    // Rest of code
  }
}
like image 140
Brett DeWoody Avatar answered Oct 24 '22 09:10

Brett DeWoody