【发布时间】:2019-04-03 00:18:01
【问题描述】:
我有两个不相关的组件连接到 redux。一个是按钮,另一个是应用程序的主屏幕。计划是让 HomeScreen 知道何时单击该按钮。所以,我有一个动作和一个减速器来传递按钮的状态。这工作正常,只是当我第一次单击该按钮时 HomeScreen 没有收到更新。我必须单击按钮两次才能使状态通过。
添加事件操作:
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);
减速机:
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);
【问题讨论】:
标签: reactjs react-native react-redux