当 url 匹配同一路由时,React 路由器不会重新加载页面

React router is not reloading page when url matches the same route

我有以下路线。当我在 /createtest 页面并执行 history.push(/createtest/some-test-id) 因为它匹配相同的路由组件时,它不会重新加载。 有没有什么聪明的办法?或者我需要检查 match 参数并实现重新加载的逻辑?

(反应 16,路由器 v4)

<Route path="/createtest/:testid?/:type?/:step?/:tab?" render={(props) => <CreateTest user={user} {...props}/>}/>

查看此文档。 https://reacttraining.com/react-router/web/api/Route/exact-bool

The exact param comes into play when you have multiple paths that have similar names:

For example, imagine we had a Users component that displayed a list of users. We also have a CreateUser component that is used to create users. The url for CreateUsers should be nested under Users. So our setup could look something like this:

Now the problem here, when we go to http://app.com/users the router will go through all of our defined routes and return the FIRST match it finds. So in this case, it would find the Users route first and then return it. All good.

But, if we went to http://app.com/users/create, it would again go through all of our defined routes and return the FIRST match it finds. React router does partial matching, so /users partially matches /users/create, so it would incorrectly return the Users route again!

The exact param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url.

So in this case, we should add exact to our Users route so that it will only match on /users:

您可以将 URL 参数作为 key 提供给组件,以便在 URL 参数更改时创建一个全新的组件。

<Route
  path="/createtest/:testid?/:type?/:step?/:tab?"
  render={props => {
    const {
      match: {
        params: { testid, type, step, tab }
      }
    } = props;
    return (
      <CreateTest
        key={`testid=${testid}&type=${type}&step=${step}&tab=${tab}`}
        user={user}
        {...props}
      />
    );
  }}
/>;

你可以试试这个

const Reloadable = (props) => {
    const { location } = props
    const [key, setKey] = useState(location.key)

    if (location.key !== key) {
        setTimeout(() => setKey(location.key), 0)
        return null
    }
    return <>{props.children}</>
}

<Route path="/" exact render={({ history, location }) => (
    <Reloadable location={location}>
        <SomeComponent />
    </Reloadable>)}
/>

我认为这样的事情可能有助于解决您的问题

<Route key={'notReloadableRoute'} ... /> 

(静态键,如常规字符串)