我无法想象如何使用axios和redux-thunk发布帖子请求,以便在查询后调度操作 .
这是我的请求模块
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的工作发布请求,然后响应被发送到reducer?
谢谢!
更新
经过广泛的测试和来回,我认为问题是以redux形式 . 正如迈克尔指出的那样,调度应该有效 . 我使用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._%+-]+@[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);
post请求位于onSubmit方法中 . 调用login方法,但永远不会调度返回值 .
再次感谢您的时间和帮助
3 回答
我发现了我的问题 . 感谢迈克尔的评论,这有助于我向另一个方向发展 .
问题是我的表单没有连接到redux . 我最终将connect函数添加到我的export语句中 .
而且我还必须在onSubmit中更改对登录功能的调用
无法添加评论,但我很高兴你弄清楚了 . 我想警告你,在更新版本的redux-form上,你必须在connect函数之外装饰你的表单到redux . 我遇到了这个问题,它让我疯狂地试图解决这个问题 .
更新后连接redux-form将是一个两步过程 . 例如,它看起来像这样 .
然后你的标准连接功能
希望这能为您节省未来的头痛
你的函数不应该'再次返回(调度)',因为动作的作用是返回一个函数 . 它应该是
编辑功能齐全 .