我無法計算如何使用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