Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

javascript - Keep param consistent on location change ReactJs

I am using react router v4 to change location in ReactJs.

this.props.history.push("/profile");

<Link to="/profile" />

The above code works fine.

Now I want to keep a param consistent in URL http://localhost:3000?source=test by using the same code as above.

One approach is that I find all the occurrences in the code and add condition that if params source=test exist then append it to the the URL as well but this approach doesn't look fine to me as I have add condition on every redirect, Link and history.push

Second approach that I find is that use of listener on location update given by react router

In my Main Route file

class App extends Component {

  componentDidMount() {
     this.unlisten = this.props.history.listen((location, action) => {
      if (/source=ep/.test(this.props.location.search)) {
        location.search = _startsWith(location.search, "?") ? location.search + "&source=test" : "?source=test"
      }
    });
  }
}

With this approach I can easily append the params in search query of react router but the param doesn't show up in URL.

the URL looks like this http://localhost:3000/profile and When I get search params from react-router console.log(this.props.location.search) it shows the param source=test and it's exactly what I want but In this case if user refreshes on this page the search params lost from react-router as well because it's not in the URL.

Can you guys help me to keep source=test consistent even in URL.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...