Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solve conflict for multi <Redirect /> #5270

Closed
wants to merge 1 commit into from

Conversation

tdzl2003
Copy link

@tdzl2003 tdzl2003 commented Jun 22, 2017

I'm using react-router v4 on some data analytics project, I use <Redirect /> to add some default value of query parameters to location, wish keeping data unchanged after refresh and/or copy&paste link in another browser.

This is how I did this:

export default function QueryDatePicker(props) {
  const { history, location, name } = props;
  const query = qs.parse(location.search);
  const value = query[name];
  if (!value) {
    // Add [name] query parameters.
    return (
      <Redirect to={{
        ...location,
        search: qs.stringify({
          ...query,
          [name]: moment().startOf('day').subtract(1, 'days').valueOf(),
        }),
      }}/>
    )
  }

  return (
    <DatePicker onChange={v => changeQuery(history, location, name, v)} value={moment(+value)} />
  )
}

I also have QueryRadioGroup , and use them like this:

export default function SomePage(props){
  const { location } = props;
  const query = qs.parse(location.search);
  const dataReady = !!query.date && !!query.inDays;
  const url = `/api/task1?from=${query.date}&to=${query.date}&inDays=${query.inDays}`;


  return (
    <div>
      <QueryDatePicker {...props} />
      <QueryRadioGroup {...props} name="type" values={VALID_TYPES}/>

      { dataReady && <Fetch url={url}>
        <SomeComponent />
      </Fetch> }
    </div>
  );
}

Each QueryXXX component will return a Redirect to add a query paremeter on location if missing.

The problem comes: each <Redirect /> will be mounted only once, after many history.replace() calls, only the latest one will effect. There's no chance for other Redirect to perform again.

Add a componentWillReceiveProps method to Redirect class which performs again will solve this problem, but is this dangerous? Any better idea for this case?

@timdorr
Copy link
Member

timdorr commented Jun 22, 2017

Duplicate of #5162

@timdorr timdorr closed this Jun 22, 2017
@lock lock bot locked as resolved and limited conversation to collaborators Jan 18, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants