重新连接通过道具来不及

我正在使用react-native编写简单的音频播放器。 我有一个关于通过react-redux connect方法将道具传递给组件的问题。

这是我的容器代码:

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);

这里有很少的组件方法

  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>
   ); 
 }

当歌曲加载和存储值“播放”成为true时,组件方法componentWillReceiveProps调用,但this.props.playing标志为false,尽管它在mapStateToProps中为true。 但是在componentWillReceiveProps呈现调用之后,this.props.playing在此处为true。


这是预期的行为,在componentWillReceivePropsthis.props是对以前道具的引用。 您将要使用nextProps的参数componentWillRecieveProps

componentWillReceiveProps(nextProps) {
  if (nextProps.playing) {
    // Rest of code
  }
}
链接地址: http://www.djcxy.com/p/52163.html

上一篇: redux connect passes props too late

下一篇: Trying to integrate redux into react application. Webpack is choking on store.js