我有两个不相关的组件连接到 redux。一个是按钮,另一个是应用程序的主屏幕。该计划是让 HomeScreen 知道何时单击该按钮。因此,我有一个操作和一个 reducer 来传递按钮的状态。除了当我第一次单击该按钮时主屏幕没有接收更新之外,这工作正常。我必须单击按钮两次才能使状态恢复正常。
添加事件操作:
import { PLUS_INCIDENT } from './types';
export const plusIncident = pressed => (dispatch) => {
console.log('2: action: ', pressed);
dispatch({
type: PLUS_INCIDENT,
payload: pressed
});
};
按钮组件:
// The action
import { plusIncident } from '../redux/actions/plusIncident';
import { connect } from 'react-redux';
class AddIncidentButton extends Component {
handleAddButtonPress = () => {
const { pressed } = this.state;
const { plusIncident } = this.props;
const btnState = !pressed;
this.setState({ pressed: btnState });
plusIncident(btnState);
};
...
}
...
export default connect(
null,
{ plusIncident }
)(AddIncidentButton);
reducer :
import { PLUS_INCIDENT } from '../actions/types';
const initialiState = {
pressed: false
};
function inc(state = initialiState, action) {
switch (action.type) {
case PLUS_INCIDENT:
return {
...state,
pressed: !action.payload
};
default:
return state;
}
}
主屏幕: componentWillReceiveProps 方法仅在单击按钮两次后才会被调用。
class HomeScreen extends React.Component {
state = {
pressed: false
};
componentWillReceiveProps(nextProps) {
const { pressed } = this.props;
if (pressed !== nextProps.pressed) {
this.setState({ pressed: !nextProps.pressed });
}
}
...
}
const mapStateToProps = state => ({
pressed: state.inc.pressed
});
export default connect(mapStateToProps)(HomeScreen);
最佳答案
尝试添加首次调用的 componentDidMount() 。收到更新后将调用 componentWillRecieveProps:
componentDidMount() {
this.setState({ pressed: !this.props.pressed});
}
希望它有效..
关于reactjs - 当状态第一次更新时,componentWillReceiveProps 不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55439888/