问题描述
我正在尝试实施 https://www.youtube.com/上描述的方法watch?v = 5gl3cCB_26M ,其中所有Redux动作都只是普通对象(原本是对象),API调用是由中间件完成的.
I'm trying to implement the approach described on https://www.youtube.com/watch?v=5gl3cCB_26M, where all Redux actions are just plain objects (as they were meant to be) and API calls are done by middlewares.
执行此操作后,分派的动作将不再受到重击,并且无法返回Promise
.因此,我将无法在提交处理程序中使用Formik的setSubmitting
(将isSubmitting
标志设置为false
),就像Formik文档中的代码示例以及我发现的其他教程一样.
By doing this, the dispatched actions are no longer thunks and can't return a Promise
. So I won't be able to use Formik's setSubmitting
(to set the isSubmitting
flag to false
) inside the submit handler, like the code samples on Formik docs and other tutorials I've found.
我已经通过某种丑陋的方式解决了该问题,保存了setSubmitting
的引用以供以后在componentDidUpdate
内部运行:
I've solved the issue in a kinda ugly way, saving a reference of setSubmitting
to run it later, inside componentDidUpdate
:
import React, { Component } from 'react'
import { Redirect } from 'react-router-dom'
import LoginForm from 'path/to/LoginForm'
import validationSchema from 'path/to/LoginForm/validationSchema'
import { login } from 'path/to/actionCreators'
const initialValues = {
email: '',
password: '',
}
class LoginPage extends Component {
componentDidUpdate() {
const { auth } = this.props
if (!auth.isProcessing && this.setSubmitting) {
this.setSubmitting(false)
}
}
onSubmit = (values, { setSubmitting }) => {
const { dispatch } = this.props
dispatch(login(values)))
this.setSubmitting = setSubmitting
}
render() {
const { auth } = this.props
if (auth.user.uid) {
return <Redirect push to="/" />
}
return (
<div className="login-panel">
<h1>Login</h1>
<Formik
initialValues={initialValues}
onSubmit={this.onSubmit}
render={LoginForm}
validationSchema={validationSchema}
/>
</div>
)
}
}
const mapStateToProps = state => ({
auth: state.auth,
})
export default connect(mapStateToProps)(LoginPage)
我该如何以更优雅"的方式进行操作?
How can I do it in a more "elegant" way ?
推荐答案
您可以实现回调.只需在中间件中调用onSuccess
或onError
回调并在组件中处理它们即可.
You could implement callbacks. Just invoke an onSuccess
or onError
callback in your middleware and handle them in your component.
// component.js
class LoginPage extends Component {
// ...
onSubmit = (values, { setSubmitting }) => {
const { dispatch } = this.props
setSubmitting(true);
dispatch(
login(
values,
() => setSubmitting(false), // success callback to be invoked in middleware
(message) => { // error handler invoked in middleware catch
this._handleErrorMessage(message);
setSubmitting(false);
},
)
);
}
}
// actions.js
function loginAction(payload, onSuccess, onError) {
return {
type: LOGIN,
payload,
onSuccess,
onError,
}
}
// middleware.js
function handleLogin(action) {
const { payload, onSuccess, onError } = action;
try {
// login...
onSuccess('hurray!');
} catch(error) {
const { message } = error;
onError(message);
}
}
这篇关于如何在提交处理程序之外运行setSubmitting()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!