react router Link doesn't cause rerender when

2020-07-18 11:32发布

I'm using react router v4, had some issue reloading the page (not window.location.reload). I better give a real use case to explain the issue, we use a social network app as the example:

  1. user A commented a post by user B, a notification appear in user B page.
  2. user B clicked on the notification, we do this.props.history.push('/job/' + id'), it worked, hence user B went to job/123 page.
  3. user A commented again, new notification appear in user B page, while user B still remain on the job/123 page, he clicked on the notification link and triggered this.props.history.push('/job' + id'). But he won't see the page rerender, he DID NOT see the latest comment because the page does nothing.

3条回答
看我几分像从前
2楼-- · 2020-07-18 11:48

You are describing 2 different kinds of state changes.

In the first scenario, when user B is not at the /job/:id page and he clicks a link you get a URL change, which triggers a state change in the router, and propagates that change through to your component so you can see the comment.

In the second scenario, when user B is already at the /job/:id page and a new comment comes through, the URL doesn't need to change, so clicking on a link won't change the URL and won't trigger a state change in the router, so you won't see the new content.

I would probably try something like this (pseudo code because I don't know how you're getting new comments or subscribing via the websocket):

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

class Home extends React.Component {
  render() {
    return (
      <div>
        <h1>The home page</h1>

        {/* This is the link that the user sees when someone makes a new comment */}
        <Link to="/job/123">See the new comment!</Link>
      </div>
    );
  }
}

class Job extends React.Component {
  state = { comments: [] };

  fetchComments() {
    // Fetch the comments for this job from the server,
    // using the id from the URL.
    fetchTheComments(this.props.params.id, comments => {
      this.setState({ comments });
    });
  }

  componentDidMount() {
    // Fetch the comments once when we first mount.
    this.fetchComments();

    // Setup a listener (websocket) to listen for more comments. When
    // we get a notification, re-fetch the comments.
    listenForNotifications(() => {
      this.fetchComments();
    });
  }

  render() {
    return (
      <div>
        <h1>Job {this.props.params.id}</h1>
        <ul>
          {this.state.comments.map(comment => (
            <li key={comment.id}>{comment.text}</li>
          ))}
        </ul>
      </div>
    );
  }
}

ReactDOM.render(
  <BrowserRouter>
    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/job/:id" component={Job} />
    </Switch>
  </BrowserRouter>,
  document.getElementById("app")
);

Now the page will get updated in both scenarios.

查看更多
一夜七次
3楼-- · 2020-07-18 11:58

It seems to be a common scenario in many cases. It can be tackled using many different approaches. Check this stackoverflow question. There are some good answers and findings. Personally this approach made more sense to me.

location.key changes every single time whenever user tries to navigate between pages, even within the same route. To test this place below block of code in you /jod/:id component:

componentDidUpdate (prevProps) {
    if (prevProps.location.key !== this.props.location.key) {
      console.log("... prevProps.key", prevProps.location.key)
      console.log("... this.props.key", this.props.location.key)
    }
  }

I had this exact same situation. Updated state in componentDidUpdate. After that worked as expected. Clicking on items within the same route updates state and displays correct info.

I assume (as not sure how you're passing/updating comments in /job/:id) if you set something like this in your /job/:id component should work:

componentDidUpdate (prevProps) {
    if (prevProps.location.key !== this.props.location.key) {

      this.setState({
        comments: (((this.props || {}).location || {}).comments || {})
      })
    }
  }
查看更多
冷血范
4楼-- · 2020-07-18 12:02

You should watch updating postId in componentWillUpdate life cycle and do something from here like this:

  componentWillUpdate(np) {
    const { match } = this.props;
    const prevPostId = match.params.postId;
    const nextPostId = np.match.params.postId;
    if(nextPostId && prevPostId !== nextPostId){
      // do something
    }
  }
查看更多
登录 后发表回答