Vit*_*pka 4 javascript reactjs react-native redux react-redux
我正在使用react-native编写简单的音频播放器.我有一个关于在反应 - 还原连接方法中将道具传递给组件的问题.
这是我的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);
Run Code Online (Sandbox Code Playgroud)
这里有一些来自组件的方法
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>
);
}
Run Code Online (Sandbox Code Playgroud)
当歌曲加载并存储值'playing'变为true时,components方法componentWillReceiveProps调用,但this.props.playing标志为false,尽管mapStateToProps中为true.但是在componentWillReceiveProps渲染调用之后,this.props.playing在那里是真的.
这是正常现象,在componentWillReceiveProps,this.props是以前的道具的参考.你会想要使用nextProps参数componentWillRecieveProps.
componentWillReceiveProps(nextProps) {
if (nextProps.playing) {
// Rest of code
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
682 次 |
| 最近记录: |