How can I rerender a React component on path chang

2019-07-16 08:58发布

问题:

import React, { Component } from "react";
import PostContainer from "../../components/PostContainer";
import { connect } from "react-redux";
import { withRouter } from "react-router";
import API from "../../utils/API";

class User extends Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: [],
      user: []
    };
  }

  componentDidMount() {
    API.findUserById(this.props.match.params.id)
      .then(res => {
        console.log(res);
        this.setState({ user: res.data });
      })
      .catch(err => console.log(err));
  }

  render() {
    return (
      <div>
        <div>{console.log(JSON.stringify(this.state.user))}</div>
        <div className="container-fluid">
          <div className="row">
            <div className="col-8">
              {this.state.posts.map(post => (
                <PostContainer post={post} />
              ))}
              <h1>No Posts To Show!</h1>
            </div>
            <div className="col-2 sidebar-container">
              <p>{this.state.user.username}</p>
              <p>{this.state.user.id}</p>
              <p>{this.state.user.email}</p>
              <p>{this.state.user.profileImg}</p>
            </div>
            <div className="col-2 sidebar-container">
              <p>{this.props.username}</p>
              <p>{this.props.id}</p>
              <p>{this.props.email}</p>
              <p>{this.props.profileImg}</p>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    username: state.auth.username,
    id: state.auth.id,
    email: state.auth.email,
    profileImg: state.auth.profileImg
  };
};

export default withRouter(connect(mapStateToProps)(User));

The code above belongs to any route with the path "/user/:id". This renders fine with no issues, however, if I click on a link that brings me to a different "/user/:id", the path changes, but the component will not rerender. Is it possible to "trick" or force react into rerendering the component?

Here is the code for the routing:

import { Switch, Route, BrowserRouter as Router } from "react-router-dom";
import NavbarFix from './components/NavbarFix';
import AuthRoute from "./utils/AuthRoute";
import AlreadyAuth from "./utils/AlreadyAuth";
import React, { Component } from "react";
import Navbar from './components/Navbar';
import NoMatch from "./pages/NoMatch";
import Submit from './pages/Submit';
import SignUp from "./pages/SignUp";
import LogIn from "./pages/LogIn";
import Posts from "./pages/Posts";
import User from "./pages/User"
// import Test from "./pages/Test";
import "./App.css";

class App extends Component {  
  render() {
    return (
      <Router>
        <div>
          <Navbar />
          <NavbarFix />
          <Switch>
            <Route exact path="/" component={AuthRoute(Posts)} />
            <Route exact path="/submit" component={AuthRoute(Submit)} />
            <Route exact path="/signup" component={AlreadyAuth(SignUp)} />
            <Route exact path="/login" component={AlreadyAuth(LogIn)} />
            <Route exact path="/user/:id" component={AuthRoute(User)} />
            <Route exact path="/item/:itemId" component={AuthRoute(User)} />
            <Route component={NoMatch} />
          </Switch>
        </div>
        </Router>
    );
  }
}

export default App;

回答1:

Redux will update the component whenever the return of mapStateToProps changes, so you could map the parameter in there:

const mapStateToProps = (state, ownProps) => {
  return {
    username: state.auth.username,
    id: state.auth.id,
    email: state.auth.email,
    profileImg: state.auth.profileImg,
    viewUserId: ownProps.match.params.id,
  };
};

This in combination with componentDidUpdate should work for you, since componentDidMount will only run when the component is mounted, not updated.

You could also use a sidekick, such as Redux Sagas, Thunk, etc. to perform these calls in the background for you and update the store accordingly.