【问题标题】:Re-render React Component when query string changes查询字符串更改时重新渲染 React 组件
【发布时间】:2018-12-06 04:51:42
【问题描述】:

我对 React 很陌生,如果这只是重复,我深表歉意 - 我试图寻找其他问题的解决方案,但没有一个对我有帮助。

我想要一个 React 组件在页面的查询字符串发生变化时重新渲染。我有一个基本的联系表格,我正在使用通过查询字符串传递的值预先填充一个字段。我的理解是,React 应该在组件的状态或组件发生变化时重新渲染组件,并且看到查询字符串是道具的一部分(this.),然后我认为这很容易,但这似乎并非如此我。

路线

<Route exact path="/contact-us" component={ContactUs} />

组件

import React, { PureComponent, Fragment } from 'react';
import bannerImage from './../../assets/images/contact-banner.jpg';
import QueryString from 'query-string';

class ContactUs extends PureComponent {
  render() {
    return (
      <Fragment>
        <CommonBanner banner={bannerImage} title="Contact us" />
        <ContactUsForm tripName={QueryString.parse(this.props.location.search).tripName)} />
      </Fragment>
    );
  }
}

export default ContactUs;

我希望在以下情况下重新呈现联系表单:用户从通过查询字符串发送行程名称的位置单击,然后单击链接到的页面标题中的“联系我们”按钮再次联系我们页面,但查询字符串中没有行程名称。这应该会删除行程名称字段的预填充。

更新

我注意到,如果我在浏览器中手动从 URL 中删除查询字符串,则该字段会按预期空白。只有当我点击菜单中的链接时,它才链接到“联系我们”,似乎什么都没有发生。

【问题讨论】:

  • 是的,我以前在那里看到过你的回答。我宁愿不要弄乱路由器,如果可能的话,只为这个组件提供一个解决方案。
  • 好吧,我们不是在搞乱路由器,您可以根据自己的要求选择使用自定义的 withRouter 或默认的,而且,这是一个足够通用的解决方案,您可以在整个过程中使用应用
  • 但是为什么即使道具发生变化,组件也不会重新渲染?
  • this.props.location.search 已更改...

标签: javascript reactjs routing query-string react-router-v4


【解决方案1】:

想通了。毕竟这不是由ContactUs 组件引起的。这是由使用 Formik 并设置初始值的子组件 ContactUsForm 引起的,如下所示:

<Formik
  initialValues={{
  firstName: '',
  surName: '',
  email: '',
  message: '',
  tripName: this.props.tripName || '',
}}
...
>

如果使用enableReinitialize - https://github.com/jaredpalmer/formik#enablereinitialize-boolean 更改初始值,您需要允许 Formik 重新初始化表单

<Formik
  initialValues={{
  firstName: '',
  surName: '',
  email: '',
  message: '',
  tripName: this.props.tripName || '',
}}
enableReinitialize={true}
...
>

【讨论】:

    【解决方案2】:
    componentDidUpdate(prevProps, prevState) {
      if (prevProps.match.params.'queryVariable' !== this.props.match.params.'queryVariable') {
      //either 
        this.forceUpdate()
     //or
        this.setState({
          something:something
        })
      }
    }
    

    把你的查询参数变量例子 prevProps.match.params.id 和 this.props.match.params.id

    【讨论】:

    • 这似乎也不起作用。它调用forceUpdate,但仍然没有任何反应。
    • 查询参数与 url 参数不同。查询参数是? 之后的参数,如?param1=value1
    猜你喜欢
    • 2021-07-13
    • 1970-01-01
    • 2023-03-28
    • 2021-11-06
    • 1970-01-01
    • 2019-07-05
    • 2021-08-13
    • 2019-02-27
    • 2020-12-24
    相关资源
    最近更新 更多