【发布时间】:2019-08-25 06:00:52
【问题描述】:
我有一个组件,它有一个表单,此时在提交按钮上执行 clic,我调用一个函数 handleSubmit(它在我的组件上),这个函数通过 dispatch 和这个动作调用一个动作,我调用一个服务(HTTP 请求)。
处理提交
handleSubmit = (e) => {
e.preventDefault()
const { validateFields } = this.props.form;
validateFields((err, params) => {
if (!err) {
const { user, dispatch } = this.props;
let response = dispatch(actions.addDevice(params))
console.log(response); //Response is undefined
}
});
}
actions.addDevice
function addDevice(params){
return (dispatch, getState) => {
let { authentication } = getState();
dispatch(request({}));
service.addDevice(params, authentication.user.access_token)
.then(
response => {
if(response.status === 201) {
dispatch(success(response.data));
}
return response;
},
error => {
dispatch(failure(error.toString()));
dispatch(alertActions.error(error.toString()));
}
)
}
function request(response) { return { type: constants.ADD_DEVICE_REQUEST, response } }
function success(response) { return { type: constants.ADD_DEVICE_SUCCESS, response } }
function failure(error) { return { type: constants.ADD_DEVICE_FAILURE, error } }
}
service.addDevice
function addDevice(params, token){
return axios({
url: 'http://localhost:5000/user/add-device',
method: 'POST',
headers: { 'Authorization': 'Bearer ' + token},
data: {
data1: params.data1,
data2: params.data2,
data3: params.data3
}
})
.then(function(response) {
return response;
})
.catch(function(error) {
return error.response;
});
}
我想在我的组件中获得响应以便能够进行验证,但由于请求是异步的,我永远无法获得响应并且只打印一个未定义的变量。如何获得响应同步?或者我需要做什么才能进行验证?
【问题讨论】:
-
要在组件中使用响应,您还需要做 3 件事:在
ADD_DEVICE_REQUEST上创建一个 reducer 以更新 redux 状态,创建一个选择器函数来获取您在状态中更改的变量,然后使用mapStateToProps函数向组件添加一个等于该选择器结果的道具
标签: javascript reactjs react-redux