简体   繁体   中英

Warning : invalid props and should not use Route component and children in same route

I am using BrowserRouter with App as parent component and UserInfo as child. Unable to fetch data I am getting errors as mentioned in question I am using BrowserRouter with App as parent component and UserInfo as child. Unable to fetch data I am getting errors as mentioned in question

// This is my index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { BrowserRouter, Switch, Route } from 'react-router-dom'

var UserInfo = require('./Components/UserInfo');

var routes = (
    <BrowserRouter>
        <Route path="/" component={App}>
            <Switch>
                <Route path="user/:username" component={UserInfo} />
            </Switch>
        </Route>
    </BrowserRouter>
);

ReactDOM.render(routes, document.getElementById('root'));
registerServiceWorker();

//App.js

import React, { Component } from 'react';
import './App.css';
import PropTypes from "prop-types";
import { browserHistory } from 'react-router';

var history = require('react-router').browserHistory;

class App extends Component {
  static contextTypes = {
    router: PropTypes.object
  }
  constructor(props, context) {
     super(props, context);
  }
  submitUser(event) {
    console.log(this.refs.inputUser.value);
    event.preventDefault();
    this.context.router.history.push('/user/${this.refs.inputUser.value}');
  }

  render() {
    return (
      <div>
        <nav className="uk-navbar-container uk-margin" uk-navbar="true">
          <div className="uk-navbar-left">

            <a className="uk-navbar-item uk-logo" href="/">  Github search  &nbsp;
              <span uk-icon="icon: github; ratio: 2.2" className="uk-margin-large-right"></span>
            </a>

            <div className="uk-navbar-item  uk-navbar-right">
              <form onSubmit={this.submitUser}>
                <input className="uk-input uk-form-width-medium"
                  type="text" placeholder="Github UserName...." ref="inputUser" />
                &nbsp;&nbsp;
                <button className="uk-button uk-button-primary">Search &nbsp;
                <span uk-icon="search" className="uk-margin-small-right"></span>
                </button>
              </form>
            </div>
            <div className="uk-navbar-item  uk-navbar-right"></div>
          </div>
        </nav>

        <div className="uk-container-large">
          {this.props.children}
        </div>
      </div>

    );
  }
}

export default App;

//UserInfo.js

import React, { Component } from 'react';
import { BrowserRouter, Link } from 'react-router-dom'

var $ = require('jquery');

class UserInfo extends Component {
    constructor(props) {
        super(props)
    }
    getInitialState() {
        return {};
    }

    componentDidMount() {
        this.fetchData();
    }
    componentDidUpdate(prevProps) {
        if (prevProps.params.username !== this.props.params.username) {
            this.fetchData();
        }
    }

    fetchData() {
        $.getJSON('https://api.github.com/users/${this.props.params.username}')
            .then(res => res.json())
            .then((user) => {
                this.setState = { user: user }
            });
    }

    render() {
        if (!this.state.user) {
            return (
                <div className="uk-child-width-1-3@s uk-grid-match">Loading......</div>
            )
        }
        var user = this.state.user;

        return (
            <div className="uk-child-width-1-3@s uk-grid-match" uk-grid>
                <Link to={`/user/${user.login}`}>
                    <div className="uk-grid-small uk-flex-middle" uk-grid>
                        <div className="uk-width-auto">
                            <img className="uk-border-circle" width="60" height="60"
                                src={user.avatar_url} />>
                 </div>
                        <div className="uk-width-expand">
                            <h3 className="uk-card-title uk-margin-remove-bottom">
                                {user.login} ({user.name})
                            </h3>
                            <p className="uk-text-meta uk-margin-remove-top">
                                {user.bio}
                            </p>
                        </div>
                    </div>
                </Link>
            </div>
        );
    }
}

export default UserInfo;

You have some errors in the UserInfo Component.

  1. You have not set the Initial State of user in the constructor.
  2. No need for another then in $.getJSON().You already getting the response , just setState the user with the response and you are good to go.

     class UserInfo extends React.Component { constructor(props) { super(props) this.state={ user : "", } } componentDidMount() { this.fetchData(); } componentDidUpdate(prevProps) { if (prevProps.params.username !== this.props.params.username) { this.fetchData(); } } fetchData() { $.getJSON('https://api.github.com/users/subhanshu') .then((res) => { this.setState({ user : res }) },this); } render() { if (!this.state.user) { return ( <div className="uk-child-width-1-3@s uk-grid-match">Loading......</div> ) } var user = this.state.user; return ( <div className="uk-child-width-1-3@s uk-grid-match" uk-grid> <Link to={`/user/${user.login}`}> <div className="uk-grid-small uk-flex-middle" uk-grid> <div className="uk-width-auto"> <img className="uk-border-circle" width="60" height="60" src={user.avatar_url} />> </div> <div className="uk-width-expand"> <h3 className="uk-card-title uk-margin-remove-bottom"> {user.login} ({user.name}) </h3> <p className="uk-text-meta uk-margin-remove-top"> {user.bio} </p> </div> </div> </Link> </div> ); } } 

Your <BrowserRouter> should be like,

<BrowserRouter>
  <Switch>
    <Route path="/" component={App}>
  </Switch>
</BrowserRouter>

and if App is not a generic parent and is used only to show UserInfo , inside the App component's render you can give,

<div className="uk-container-large">
   <Route path="user/:username" component={UserInfo} />
</div>

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