gpt4 book ai didi

javascript - 在react-redux中异步函数成功后如何调用组件的方法?

转载 作者:行者123 更新时间:2023-11-28 17:29:57 25 4
gpt4 key购买 nike

主要成分:

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 中看到 只有在成功调用 post 请求后,我才必须调用(主要组件的)next() 方法。 next() 。 (我跳过了一些代码,因为它太长了)。如果我在 postStage 之后调用(就像我在 Child 中所做的那样),我无法保证 api 调用成功。我在哪里以及如何调用它?

我在 Child 中有一个按钮,其中有一个 eventHandler - handleSubmit

最佳答案

您应该将 incompleteStage 存储在您的商店中并让 reducer 更改它。当异步完成时分派(dispatch)一个操作,reducer 应该更改 incompleteStage 数组,这样你的组件就会更新它的 props。

关于javascript - 在react-redux中异步函数成功后如何调用组件的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50686422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com