警告:失败的 prop 类型:提供给‘Route’ 的 prop‘component’ 无效 - react-router-dom
2020-03-11
6438
我想解决这个警告。我将 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 传递到子组件 App.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()
谢谢!
2个回答
将此
<Route component={<NotFound /> />} />
更改为:
<Route component={NotFound} />
对于此类库而言,这是相当标准的行为。他们希望像这样呈现组件:
<component />
,而不是像这样:
{component>
。
Asher Gunsay
2020-03-11
@Asher 的答案应该可行,但如果您有想要传递的 props,那么您可以在创建 React 元素的内联函数中传递该组件:
<Switch><Route component={() => <NotFound message={notFoundMessage} />}/></Switch>
资源: https://ui.dev/react-router-v4-pass-props-to-components/
Mike Dubs
2020-09-17