React-redux连接太晚了

时间:2017-05-26 11:42:37

标签: javascript reactjs react-native redux react-redux

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

这是我的Container代码:

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

当歌曲加载并存储价值&#39;播放&#39;变为true,组件方法componentWillReceiveProps调用,但this.props.playing标志为false,尽管它在mapStateToProps中为true。 但是在componentWillReceiveProps渲染调用之后,this.props.playing就为真。

1 个答案:

答案 0 :(得分:7)

这是预期的行为,在componentWillReceiveProps中,this.props是对先前道具的引用。您需要使用nextProps的{​​{1}}参数。

componentWillRecieveProps