Redux存储:如何订阅组件中的实际更改



我的几个组件应该只渲染一次,从那时起,我只想让它们侦听全局存储中的更改并采取相应的行动。但我做不到:store.subscriberedux-watch我只在数据被调度时尝试解雇,但在商店实际更改时没有尝试解雇,这意味着相应的功能不能使用this.props.bla,因为它还没有更新。是否有某种解决方案可以在渲染函数中不使用bla的情况下知道

this.props.bla组件示例:

import React, { Component } from 'react';
import { connect } from 'react-redux';
const mapStateToProps = state => {
return { 
position: state.position //<== when to know for sure it changed?
};
};
class MyComp extends Component {
constructor(props) {
super(props);    
this.state = {
number: 0
};
store.subscribe(() => {
const currentState = store.getState();
// even if I have the updated value here in currentState, there are not guarantees this.props.position already changed.
});
}
calculate = ()=>{
// Do some calculation with this.props.position and change the number.
}
render(){
return <div>{this.state.number}</div>;
}
}
export default connect(mapStateToProps)(MyComp);

当您想要"响应";对于特定的道具值更新,则应该实现componentDidUpdate生命周期方法。在您的情况下,如果您需要知道注入的position道具值何时更新,请添加一个条件,将以前的position道具值与当前的position道具值进行比较。

componentDidUpdate(prevProps) {
if (prevProps.position !== this.props.position) {
// position value updated!
}
}

最新更新