简体   繁体   English

警告:道具无效,请勿在同一路线中使用路线组件和子级

[英]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. 我将BrowserRouter和App作为父组件,将UserInfo作为子组件。 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. 无法获取数据我遇到了问题,我正在使用BrowserRouter,其中App作为父组件,而UserInfo作为子组件。 Unable to fetch data I am getting errors as mentioned in question 无法获取数据,我遇到了上述问题

// This is my index.js //这是我的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 //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 //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. 您在UserInfo组件中有一些错误。

  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. 然后在$ .getJSON()中不需要另一个。您已经获得了响应,只需将用户与响应一起设置为State,就可以了。

     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>应该像这样,

<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, 如果App不是通用父对象,并且仅用于显示UserInfo ,则可以在App组件的渲染中提供该信息,

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 警告:道具类型失败:提供给“路线”的道具属性无效。 在途中 - Warning: Failed prop type: Invalid prop `component` supplied to `Route`. in Route 路由组件作为 Vue 中的道具 - Route component as props in Vue 警告:道具类型失败:提供给“路线”的道具“组件”无效 - Warning: Failed propType: Invalid prop 'component' supplied to 'route' 警告:失败的 propType:提供给 `Route` 的 prop`component` 无效 - Warning: Failed propType: Invalid prop `component` supplied to `Route` 警告:道具类型失败:提供给“路由”的道具“组件”无效:道具不是路由中的有效 React 组件 - Warning: Failed prop type: Invalid prop 'component' supplied to 'Route': the prop is not a valid React component in Route Angular 7子组件路径,无父路径 - Angular 7 children component route without parent route 在运行时将 props 传递给 Route 中的组件 - Pass props to a component in a Route at runtime 将“元素”道具传递给“路线”组件 - Passing "element" props to "Route" component 无法将道具从路线道具传递给组件 - Cannot pass props to component from an Route Props 布局不是<route>成分。 的所有子组件<routes>必须是一个<route>或者<react.fragment> . 我应该如何克服这个错误?</react.fragment></route></routes></route> - Layout is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>. How should I overcome this error?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM