周天磊
周天磊

Reputation: 21

react router query parameters changed component will unmount

When query parameters changed, the same component will unmount and then mount.for example: I have a url like /admin and also have a component called Admin. In Admin, there are some inputs for searching. I add a query parameters after /admin like /admin?userId=123.The componet's componentDidMount will excute again. Is there any way to prevent this?

Upvotes: 2

Views: 577

Answers (3)

Natan Severo
Natan Severo

Reputation: 3

You can use the URL interface to set query string values without unmount and mount your components:

const queryStringValue = 'bar'

const url = new URL(window.location.toString());
url.searchParams.set('foo', queryStringValue);
window.history.replaceState(null, '', url.toString());

Also, this solution won't add a new item in browser navigation stack

Upvotes: 0

周天磊
周天磊

Reputation: 11

and setting likes this 
export default function (history, app) {
  return (
    <Switch>
      <Route exact path='/admin/settings/user' component={getComponent(User,app,userModel)} />
      <Route path='/admin/settings/user/:id' component={getComponent(UserEdit,app,userModel)} />
      <Route path='/admin/settings/role' component={getComponent(Role,app,roleModel)} />
      <Route path='/admin/settings/menu' component=
    </Switch>
  )
}

getComponent is a layload component.

Upvotes: 1

周天磊
周天磊

Reputation: 11

@Alex Brazh I used v4 and the router likes this;

<Router>
      <Switch>
        <Route exact path='/' component={getComponent(Login,app,loginModel)}/>
        <Route path='/admin' render={ props => (
          <Layout>
            { settings(history, app) }
          </Layout>
        )}/>
        <Route path='/finance' render={ props => (
          <Layout>
            { finance(history, app) }
          </Layout>
        )}/>
</Switch>
</Router>

Upvotes: 0

Related Questions