[英]React router basic implementation
I am trying to implement React router and I have a class called App from which I want to call ExpenseApp. 我正在尝试实现React路由器,并且有一个名为App的类,我想从中调用ExpenseApp。 For ExpenseApp to work, it requires 'data' which I want to pass.
为了使ExpenseApp正常工作,它需要我要传递的“数据”。 Also, my first page of get loaded should be ExpenseApp.
另外,我要加载的第一页应该是ExpenseApp。 As far as I understood react-router, the class name to be specified in the '/' path is the first page to be loaded.
据我了解react-router,在“ /”路径中指定的类名称是要加载的第一页。 The question is how can I pass data from react router to the component.
问题是如何将数据从React Router传递到组件。
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'))
And normally when I was displaying the component without using the react-router, I was doing something like 通常,当我在不使用react-router的情况下显示组件时,我正在做类似的事情
I am still confused with the concepts of react-router, how can I implement this? 我仍然对react-router的概念感到困惑,如何实现呢?
As far as I know, you usually would want to fetch data from within the component, but if it is not possible or you do not want to do this, you could try using decorateComponentWithProps
( https://github.com/belle-ui/decorateComponentWithProps ) 据我所知,您通常希望从组件内部获取数据,但是如果不可能或不想这样做,则可以尝试使用
decorateComponentWithProps
( https://github.com/belle-ui / decorateComponentWithProps )
import decorateComponentWithProps from 'decorate-component-with-props';
// ...
<Route path='/' component={decorateComponentWithProps(ExpenseApp, {data})} />
Given that the ExpenseApp
's prop name is data
假设
ExpenseApp
的prop名称是data
Edit: As found out in the comments, you also need to change 编辑:如评论中所示,您还需要更改
import {Switch, BrowserRouter, Route} from 'react-router-dom'
to 至
import {Switch, BrowserRouter as Router, Route} from 'react-router-dom'
For the code to work, or you can also change the usage of <Router />
to <BrowserRouter />
为了使代码正常工作,或者您也可以将
<Router />
的用法更改为<BrowserRouter />
maybe you can try this one : 也许你可以试试这个:
<Router>
<Route exact path='/' render={() => <ExpenseApp data={data} />}/>
<Route path='fullblog' component={FullBlog}/>
</Router>
this is using react router v4, hope can solve your issue :) 这是使用React Router v4,希望可以解决您的问题:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.