我正在使用redux-form和redux-api-middleware编写一个React / Redux应用程序,并使用RSAA生命周期编写一个'm having trouble integrating redux-form' s onSubmit
函数 .
redux-form文档说 onSubmit
handler should return一个Promise . 在承诺上调用 resolve
之前,表单的 submitting
prop将是 true
.
但是,在这个应用程序中,我的API调用目前不使用promises(例如,通过 fetch
) . 我通过调度 [CALL_API]
RSAA操作和reducing redux-api-middleware's response actions.进行API调用
问题代码
class MyReduxFormContainer extends Component {
render() {
return (
<MyReduxForm submit={this.props.submit} />
)
}
}
const mapDispatchToProps = (dispatch) => {
return {
submit: function(values, dispatch) {
dispatch({
[CALL_API]: {
method: 'PATCH',
types: [
{
type: 'REQUEST',
endpoint: '...',
body: JSON.stringify(values)
},
'SUCCESS',
'FAILURE'
]
}
});
// Problem: redux-api-middleware-style API calls normally don't leverage promises.
// Out of the box, this library doesn't offer a promise to return.
}
}
};
export default connect(
// ...
mapDispatchToProps
)(MyReduxFormContainer)
可能的解决方案
I could pass a promise through the payload RSAA callback, 然后可以在API响应之后解析/拒绝承诺,但这似乎违反了"action creators should't cause side-effects."授予redux-api-middleware似乎弯曲此规则的规则 .
I could in theory just use fetch inside the onSubmit handler ,而不是redux-api-middleware,但这并非如此,例如,设置默认 Headers ,去驼峰/驼峰有效载荷等 .
有没有人有使用redux-form和redux-api-middleware的经验?
If it were just redux-api-middleware, 我原本希望通过在减少 ACTION_TYPE_[REQUEST|SUCCESS|FAILURE]
动作类型时改变表单的状态来简单地改变表单的 submitting
prop . 但是从减速器直接修改表单的状态似乎是非标准的并且可能存在风险 . redux-form实现的示例似乎强调redux-form状态应该是透明的/只是间接操作 .
任何想法/指针将不胜感激!
相关的GitHub问题
终极版的API中间件:
终极版形式:
2 回答
最近我发现很优雅和通用的方式结合起来 . Here is article with explanation
由于缺乏更好的解决方案,我现在正在redux-form
submit
处理程序中将我的dispatch({[CALL_API]})
调用包含在Promise中 .最后我对这个代码架构非常不满意,此时我认为标准
fetch
用法比redux-api-middleware
更好 .API响应之后的触发效果足够标准作为一个问题,应该有比这种回调嵌套更优雅的解决方案,例如,使用承诺链 .