我正在使用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 = [
<FlatButton
label="Cancel"
onTouchTap={this.handleClose}
/>,
<FlatButton
label="Submit"
onTouchTap={this.props.ajaxRequest}
/>,
];
return (
<div>
<MenuItem primaryText="Make a request" onTouchTap={this.handleOpen}/>
<Dialog
title="Make a request"
actions={actions}
modal={true}
open={this.state.open}
onRequestClose={this.handleClose} />
</div>
);
}
}
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),
]
}
2 回答
您可以使用
componentWillReceiveProps()
,只要您的组件获得redux属性/状态更新,就会调用它 . 在那里,您可以对redux状态更改做出反应并相应地设置本地组件状态 .在您的示例中,它将是:
这正是您定义的所需行为 . Imo你还应该处理其他情况并更动态地设置state.open,但这超出了问题的范围 .
供参考,请参见此处:https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops
你可以使用componentWillReceiveProps();
例:
随便在你的代码中尝试它 . 这个 function is automatically called by React 当你的组件收到新道具时 . 我认为有几种方法可以处理它,但这就是我使用的....