【问题标题】:Can't get formik validation to work with react-router无法让 formik 验证与 react-router 一起使用
【发布时间】:2021-09-27 08:11:24
【问题描述】:

早上好,

我想要一个 react-router 链接仅在表单没有错误时转发,不幸的是,下面的代码在表单被验证之前会转发,因此不会出现错误等等。您能否指导我如何解决此问题,以便验证表单,如果没有错误,链接会进一步转发吗?

这是我的代码:

<Link to={this.props.formikProps.isValid?'mainMenu': 'itemDetail'}>{!this.props.disabled && <button className="buttons-panel__button" type="button" onClick={() => (this.props.handleSubmit(false), this.props.formikProps.isValid? '' : this.onValidationFail())} >Save</button>}</Link>

方法是(基本上只是显示弹窗错误,有效):

onValidationFail() {
    setAlertMessage("You need to fill all mandatory fields")
}

到目前为止,我取得的最好成绩是它在每种情况下都按预期工作,但如果根本没有触及表单。我尝试了几种不同的方法,包括来自 formik 的 formValidate,但由于某种原因它也不起作用。

我期待有关此案的一些提示/提示/解决方案。

【问题讨论】:

    标签: reactjs react-hooks react-router formik


    【解决方案1】:

    我认为您的解决方案看起来有点过于复杂。也许只是使用简单的表单提交,并在表单提交后将用户重定向到路由。
    它看起来像这样:

    import { Formik, Form, Field } from 'formik'
    
    class MyForm {
      render() {
        return (
          <Formik
            initialValues={...}
            onSubmit={() => {this.props.history.push('/go-somewhere')}}
          >
            <Form>
              <Field name="firstName" type="text" />
              <button type="submit">Submit</button>
            </Form>
          </Formik>
        )
      }
    }
    

    【讨论】:

    • 我使用的组件是一个类,它必须保持这种状态,所以我认为解决方案是行不通的(尽管看起来对我来说非常可靠)。
    • 类组件没问题。我已经更新了课堂示例的答案。
    • 好吧,我使用了 BrowserRouter,并将其添加到方法中:onSubmit={useHistory('/address')}> 它不起作用。我是新手,但据我所知,历史记录是自动实现的,这应该与 Router history={History} 然后 this.props.history.push('address') 的工作方式相同。跨度>
    • 但是useHistory 是一个适合功能组件的钩子。在类组件中,您可以使用this.props.history.push("address")
    • 不幸的是它抛出一个错误:“属性'历史'不存在类型'Readonly & Readonly'.ts(2339)”和历史部分始终带有下划线。
    猜你喜欢
    • 2017-02-20
    • 2022-06-20
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多