【问题标题】:React-redux connect passes props too lateReact-redux 连接传递 props 为时已晚
【发布时间】:2017-10-27 07:10:58
【问题描述】:

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

这是我的容器代码:

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

当歌曲加载和存储值 'playing' 为 true 时,组件方法 componentWillReceiveProps 会调用,但 this.props.playing 标志为 false,尽管在 mapStateToProps 中为 true。 但是在 componentWillReceiveProps 渲染调用之后 this.props.playing 在那里是真的。

【问题讨论】:

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


    【解决方案1】:

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

    componentWillReceiveProps(nextProps) {
      if (nextProps.playing) {
        // Rest of code
      }
    }
    

    【讨论】:

    • 这是一个常见的错误。不要忘记接受适合您的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2016-10-13
    • 2019-05-09
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多