[英]How to call a method of component after successful async function in react-redux?
主要组成部分:
class GettingStarted extends React.Component {
state = {
incompleteStage: ['a', 'b', 'c']
};
next = () => {
const data = this.state.incompleteStage;
// Everytime when next() gets called removes the first stage
// from incompleteStage.
this.setState({
incompleteStage: [...data.slice(1)]
});
}
render() {
const { incompleteStage } = this.state;
const { isSmallDevice, me } = this.props;
if (incompleteStage.length === 0) return null;
return (
<div>
<Child {...props}/>
</div>
);
}
}
const mapStateToProps = (state) => ({
postStageLoading: state.auth.postStageLoading,
postStageError: state.auth.postStageError
});
const mapDispatchToProps = (dispatch) => bindActionCreators({}, dispatch);
export default connect(
mapStateToProps,
mapDispatchToProps
)(GettingStarted);
子组件:
class Child extends React.Component {
handleSubmit = event => {
event && event.preventDefault();
const { postStage } = this.props;
const { next, name, nextStage } = this.props;
postStage(name, nextStage); // async call
next();
}
render() {
const { me } = this.props;
return (
<div >
<Typography
Welcome {me ? me.nameOrEmail : ''}!
</Typography>
</div>
);
}
}
const mapStateToProps = (state) => ({
});
const mapDispatchToProps = (dispatch) => bindActionCreators({
postStage
}, dispatch);
export default withStyles(styles)(connect(
mapStateToProps,
mapDispatchToProps
)(Child));
modules / index.js(由于时间太长,我只写了重要的东西)
export default (state = initialState, {type, payload}) => {
case types.POST_STAGE_REQUEST:
return Object.assign({}, state, {
postStageLoading: true
});
case types.POST_STAGE_SUCCESS:
return Object.assign({}, state, {
postStageLoading: false,
});
case types.POST_STAGE_FAILURE:
return Object.assign({}, state, {
postStageLoading: false,
postStageError: payload
});
}
export const postStage = (currentStage) => {
return dispatch => {
request.post('/stage', {stage: currentStage}, dispatch)
.then(({ data }) => {
if (data.success) {
dispatch({
type: types.POST_STAGE_SUCCESS,
});
dispatch(push(nextStage));
}
}
};
因此,如果您可以在Child
中看到,则仅在成功调用发布请求之后,才必须调用(主要组件的) next()
方法。 next()
。 (我跳过了一些代码,因为它太长了)。 如果我是在postStage
之后postStage
(就像我在Child中所做的那样),则我无法保证api调用成功。 我在哪里以及如何称呼它?
我在Child中有一个带有eventHandler的按钮handleSubmit
可能有一些巧妙的方法可以纠缠异步调用来执行此操作,但是坦率地说,我只是将GettingStarted
本地状态放入您的Redux存储中。 然后,要么在化POST_STAGE_SUCCESS
中的POST_STAGE_SUCCESS
操作上更改相关状态,要么调度第二个操作并用化POST_STAGE_SUCCESS
器中的状态更改状态。 这也将防止Redux状态更新速度比本地组件状态更新快的任何竞争情况(反之亦然),从而导致不同的效果。
您应该将incompleteStage存储在您的商店中,并让减速器对其进行更改。 异步完成后调度一个动作,而reducer应该更改incompleteStage数组,以便您的组件对其props进行更新。
您应该了解诺言并相应地构建应用程序。
你应该像这样运行代码
postStage(name,nextStage).then(()=> next());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.