【发布时间】: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