我正在尝试实现React路由器,我有一个名为App的类,我想从中调用ExpenseApp。要使ExpenseApp正常运行,它需要数据'我想通过。另外,我加载的第一页应该是ExpenseApp。据我所知,react-router,要在' /'中指定的类名。 path是要加载的第一页。问题是如何将数据从反应路由器传递到组件。
import React from 'react'
import ReactDOM from 'react-dom'
import {ExpenseApp} from './expense-app.js'
import {Switch, BrowserRouter, Route} from 'react-router-dom'
import {FullBlog} from './FullBlog.js'
var data=[
{
"Author":"Dan Brown",
"Book":"Inferno"
},
{
"Author":"Jeffrey Archer",
"Book":"Be careful what you wish for"
},
{
"Author":"Paulo Coelho",
"Book":"The Alchemist"
}
];
class App extends React.Component{
render(){
return(
<Router>
<Route path='/' component={ExpenseApp}/>
<Route path='fullblog' component={FullBlog}/>
</Router>
)
}
}
ReactDOM.render(<App/>, document.getElementById('container'))
通常当我在不使用react-router的情况下显示组件时,我正在做类似
的事情我仍然对react-router的概念感到困惑,我该如何实现呢?
答案 0 :(得分:1)
据我所知,您通常希望从组件中获取数据,但如果不可能或您不想这样做,则可以尝试使用decorateComponentWithProps
({{3} })
import decorateComponentWithProps from 'decorate-component-with-props';
// ...
<Route path='/' component={decorateComponentWithProps(ExpenseApp, {data})} />
鉴于ExpenseApp
的道具名称为data
编辑:如评论中所述,您还需要更改
import {Switch, BrowserRouter, Route} from 'react-router-dom'
到
import {Switch, BrowserRouter as Router, Route} from 'react-router-dom'
要使代码生效,您还可以将<Router />
的使用情况更改为<BrowserRouter />
答案 1 :(得分:1)
也许你可以尝试这个:
<Router>
<Route exact path='/' render={() => <ExpenseApp data={data} />}/>
<Route path='fullblog' component={FullBlog}/>
</Router>
这是使用react路由器v4,希望能解决你的问题:)