【问题标题】:Warning: Failed prop type: Invalid prop 'component' supplied to 'Route' - react-router-dom警告:失败的道具类型:提供给“路线”的无效道具“组件” - react-router-dom
【发布时间】:2020-03-11 22:56:46
【问题描述】:

我想解决这个警告。将 react-router-dom 添加到 App.js 后,我会收到此警告。 (应用程序本身在此警告下工作正常。)

警告信息:

index.js:1 Warning: Failed prop type: Invalid prop 'component' supplied to 'Route': the prop is not a valid React component
    in Route (at App.js:34)
    in App (at src/index.js:9)
    in Router (created by HashRouter)
    in HashRouter (at src/index.js:8)

我只是将状态向下传递给子组件表单 App.js 应用.js

import React, { Component } from 'react'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
import './App.css'
import MasterPassword from './MasterPassword'
import EncryptForm from './EncryptForm'
import NotFound from './NotFound'

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      masterPassword: null
    }
  }

  getMasterPassword = userPassword => {
    this.setState({
      masterPassword: userPassword
    })
  }

  render() {
    return (
      <Router>
        {!this.state.masterPassword
        ? <MasterPassword
            path='/ask-password'
            masterPassword={this.state.masterPassword}
            onStorePassword={this.getMasterPassword}
          />
        : <div className="App">
            <Switch>
              <Route exact path='/' render={() => <EncryptForm masterPassword={this.state.masterPassword} />} />
              <Route component={<NotFound />} />
            </Switch>
          </div>}
      </Router>
    )
  } 
}

export default App

index.js

import React from 'react'
import ReactDOM from 'react-dom'
import { HashRouter } from 'react-router-dom' 
import './index.css'
import App from './components/App'
import * as serviceWorker from './serviceWorker'

ReactDOM.render(<HashRouter>
        <App />
    </HashRouter>, document.getElementById('root'))

serviceWorker.unregister()

谢谢!

【问题讨论】:

    标签: javascript reactjs react-router react-router-dom


    【解决方案1】:

    将此&lt;Route component={&lt;NotFound /&gt;} /&gt; 更改为:&lt;Route component={NotFound} /&gt;

    对于这样的库来说,这是非常标准的行为。他们希望像这样渲染组件:&lt;component /&gt;,而不是像这样:{component}

    【讨论】:

      【解决方案2】:

      @Asher 的回答应该可以,但是如果您有想要传递的道具,那么您可以在创建 React 元素的内联函数中传递组件:

      <Switch><Route component={() => <NotFound message={notFoundMessage} />}/></Switch>
      

      资源:https://ui.dev/react-router-v4-pass-props-to-components/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-22
        • 2018-04-23
        • 1970-01-01
        • 2021-01-18
        • 1970-01-01
        相关资源
        最近更新 更多