如何在路径更改时重新渲染React组件?

时间:2018-12-17 20:29:50

标签: reactjs redux react-redux

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));

上面的代码属于路径为“ / user /:id”的任何路由。这样就可以正常工作,但是,如果我单击将我带到另一个“ / user /:id”的链接,则路径会更改,但组件不会重新呈现。是否可以“欺骗”或强行做出反应以重新渲染组件?

以下是路由代码:

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 个答案:

答案 0 :(得分:2)

只要mapStateToProps的返回值更改,Redux就会更新组件,因此您可以在其中映射参数:

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,
  };
};

componentDidUpdate结合使用应该可以为您工作,因为componentDidMount仅在安装组件时运行,而不更新。

您还可以使用助手,例如Redux Sagas,Thunk等,在后台为您执行这些调用并相应地更新商店。