我无法计算如何使用axios和redux-thunk发出请求,以便在查询后调度动作。以axios和redux形式发送请求以redux形式发送请求
这里是我的请求模块
export default {
get: function (action, url) {
return (dispatch) => {
axios.get(`${ROOT_URL}${url}`)
.then(({ data }) => {
dispatch({
type: action,
payload: data
});
});
};
},
post: function (action, url, props) {
return (dispatch) => {
axios.post(`${ROOT_URL}${url}`, props)
.then(({ data }) => {
return (dispatch) => {
dispatch({
type: action,
payload: data
});
};
});
};
}
}
的GET作品。当我调用post函数时,它会进入函数,但不会运行返回的函数。
我试着修改函数的顺序。我结束了一个工作岗位请求,但行动从未派发。
post: function (action, url, props) {
//POST works but action is not dispatched to reducer
axios.post(`${ROOT_URL}${url}`, props)
.then(({ data }) => {
return (dispatch) => {
dispatch({
type: action,
payload: data
});
};
});
}
任何想法,我怎么能实现工作后请求得到发送给我的API,然后响应被分派到减速?
谢谢!
UPDATE
经过广泛的测试和来回,我觉得这个问题是在终极版形式。正如迈克尔指出的那样,派遣应该起作用。我使用get方法在我的组件中测试了我的调用,但它不起作用。这是我的组件
const form = reduxForm({
form: 'LoginPage',
validate
});
const renderField = ({ input, label, type, meta: { touched, error } }) => (
<div className="form-group">
<label>{label}</label>
<div>
<input {...input} placeholder={label} type={type} className="form-control" />
{touched && ((error && <span>{error}</span>))}
</div>
</div>
)
class LoginPage extends Component {
displayName: 'LoginPage';
onSubmit(props) {
login(props.email, props.password);
}
render() {
const {handleSubmit} = this.props;
return (
<div className='row'>
<div className='center-block'>
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<Field name="email" type="email" label='Courriel :' component={renderField} />
<Field name="password" type="password" label='Mot de passe :' component={renderField} />
<div className="form-group text-center">
<button type="submit" className='btn btn-primary'>Se connecter</button>
</div>
</form >
</div>
</div>
);
};
};
const validate = values => {
const errors = {}
if (!values.email) {
errors.email = 'Required'
} else if (!/^[A-Z0-9._%+-][email protected][A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
errors.email = 'Invalid email address'
}
if (!values.password) {
errors.password = 'Required'
} 4
return errors
}
export default reduxForm({
form: 'LoginPage',
validate
})(LoginPage);
该发布请求是onSubmit方法。登录方法被调用,但返回值从未分派。
再次感谢您的时间和帮助
感谢头痛,但是这是我在第一个地方,它不工作。我在一个网站上看到了发送旁边的回复,所以我试了一下。 如果我在axios.post之前添加console.log,那么在两种情况下都不会调用它。 – Bruno