简体   繁体   中英

React-Router: Update route's component on new props

App.js

import React, { Component } from 'react';
import { Router, Route, browserHistory } from 'react-router';
import Login from './Login';
import Courses from './Courses';

class App extends Component {
  constructor() {
    super();

    this.state = {
      username: '',
      password: ''
    };
  }

  setCredentials = ({ username, password }) => {
    this.setState({
      username,
      password
    });
  }

  render() {
    return (
      <Router history={browserHistory}>
        <Route
          path='/'
          component={Login}
          setCredentials={this.setCredentials}
          />
        <Route
          path='/courses'
          component={Courses}
          credentials={this.state}
          />
      </Router>
    );
  }
}

The Login component takes in credentials from user, verifies them via an API call, updates App 's state with them, and then redirects to the Courses component using this.props.router.push('/courses') .

The Courses component should take in the updated credentials (ie App 's updated state) as props, and afterwards perform an API call to fetch that user's courses.

How can I detect the updates in App 's state inside the Courses component? Am I doing it wrong altogether?

Pass props to route's component correctly:

   <Route
      path='/'
      component={(props) => <Login  setCredentials={this.setCredentials} {...props} />}
      />

and NOT:

   <Route
      path='/'
      component={Login}
      setCredentials={this.setCredentials}
      />

The same for the Courses component, you pass extra-props the same way:

    <Route
      path='/courses'
      component={(props) => <Courses credentials={this.state} {...props} />}
      />

And NOT:

    <Route
      path='/courses'
      component={Courses}
      credentials={this.state}
      />

Which answers the question:

How can I detect the updates in App's state inside the Courses component?

since crendentials becomes a prop of Courses and its value state of App .

As you said with the courses component reading from props you could have a lifecycle hook like so in the courses component:

componentWillReceiveProps(nextProps) {
  if(nextProps.isAuthenticated && this.props.credentials !== nextProps.credentials) {
    // perform fetch for courses here
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM