我正在使用react / redux / react-redux来实现执行ajax请求的模式形式 .
如果我是正确的,react-redux使您能够:
将redux商店中的数据显示给您的组件
将容器中的事件调度到redux
我也使用redux-saga来处理redux触发的Ajax请求 .
但是,当从Redux触发特定事件时,我不知道如何触发操作(例如:关闭模式窗体) .
代码示例:
class MyFormDialog extends React.Component {
state = {
open: false,
};
handleOpen = () => {
this.setState({open: true});
};
handleClose = () => {
this.setState({open: false});
};
render() {
const actions = [
label="Cancel"
onTouchTap={this.handleClose}
/>,
label="Submit"
onTouchTap={this.props.ajaxRequest}
/>,
];
return (
title="Make a request"
actions={actions}
modal={true}
open={this.state.open}
onRequestClose={this.handleClose} />
);
}
}
const mapStateToProps = (state, ownProps) => {
return {
loading: state.isLoading,
success: state.success,
error: state.error,
}
};
const mapDispatchToProps = (dispatch, ownProps) => {
return {
ajaxRequest: (url, tags) => {
dispatch({type: "AJAX_REQUESTED"})
},
}
};
const ConnectedMyFormDialog = connect(
mapStateToProps,
mapDispatchToProps
)(MyFormDialog );
export default ConnectedMyFormDialog ;
Reducers的构建如下:
发送 AJAX_REQUESTED 时
isLoading = true (其他设置为false)
发送 AJAX_SUCCESS 时
success = true (其他设置为false)
发送 AJAX_FAIL 时
error = true (其他设置为false)
所以当 isLoading 从 true 更改为 false 并且 success 更改为 false 更改为 true 时,我想将 state.open 更改为false .
我不知道如何在不搞乱状态的情况下做到这一点 .
编辑:
这是我的传奇代码,用于处理事件:
function* handleAjaxRequest(action) {
try {
yield call(api.doRequest);
yield put({type: "AJAX_SUCCESS"});
} catch (e) {
yield put({type: "AJAX_FAILED"});
}
}
export default function* () {
yield [
takeEvery("AJAX_REQUESTED", handleAjaxRequest),
]
}