我按照React Router 4教程添加路线到我的Meteor / React项目:
https://medium.com/@pshrmn/a-simple-react-router-v4-tutorial-7f23ff27adf
当我点击链接时,网址会按预期更改,但路线内容不会显示。如果我刷新页面,则路由内容正确加载。这是我的代码:
版本:METEOR@1.6.0.1,react-router-dom@4.2.2
main.js
``` JSX
import React from 'react'; // eslint-disable-line no-unused-vars
import { Meteor } from 'meteor/meteor';
import { render } from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
// Start the app with imports
import '../imports/startup/accounts-config.js';
import App from '../imports/ui/layouts/App.jsx';
Meteor.startup(() => {
render((<BrowserRouter><App /></BrowserRouter>), document.getElementById('app'));
});
```
App.js
``` JSX
import React, { Component } from 'react';
import { Meteor } from 'meteor/meteor';
import { withTracker } from 'meteor/react-meteor-data';
// game components
import { MapSquares } from '../../api/map/map.js';
// User Accounts
import AccountsUIWrapper from '../AccountsUIWrapper.jsx';
import { Switch, Route, Link } from 'react-router-dom';
import Home from '../pages/home';
import Roster from '../pages/roster';
import Schedule from '../pages/schedule';
function MapSquare(props) {
return (
<span className="mapsquare" key={props.index}>{props.row}, {props.column}</span>
);
}
class App extends Component {
renderMapSquare(mapsquare) {
return (
<MapSquare
index={mapsquare._id}
/>
);
}
render() {
// avoid error while loading data
let data = [];
if (typeof this.props.mapsquares !== 'undefined') {
data = this.props.mapsquares;
}
let rows = [];
let index = 0;
if (data.length !== 0) {
for (let i = 0; i < 5; i++) {
let thisrow = [];
for (let j = 0; j < 2; j++) {
let source = data[index];
let newthing = <MapSquare
key={source._id}
row={source.row}
column={source.column}
/>;
thisrow.push(newthing);
index++;
}
rows.push(<div className="map-row" key={i}>{thisrow}</div>);
}
}
return (
<div className="game">
<AccountsUIWrapper />
<nav>
<ul>
<li><Link to='/'>Home</Link></li>
<li><Link to='/roster'>Roster</Link></li>
<li><Link to='/schedule'>Schedule</Link></li>
</ul>
</nav>
<Switch>
<Route exact path='/' component={Home}/>
<Route path='/roster' component={Roster}/>
<Route path='/schedule' component={Schedule}/>
</Switch>
<div className="game-map">
{rows}
</div>
</div>
);
}
}
// provides data to component App
export default withTracker(() => {
Meteor.subscribe('mapsquares');
return {
'mapsquares': MapSquares.find({}, { 'sort': { 'row': 1, 'column': 1 } }).fetch(),
};
})(App);
```
home.js(名册和日程表页面的工作方式相同)
``` JSX
import React from 'react';
const Home = () => (
<div>
<h1>Home</h1>
</div>
);
export default Home;
```
知道我在这里失踪的是什么吗?它几乎可以工作!
答案 0 :(得分:1)
在withRouter中包装我的数据容器似乎已经成功了:
App.js:
``` JSX
import { withRouter, Switch, Route, Link } from 'react-router-dom';
...
export default withRouter(withTracker(() => {
Meteor.subscribe('mapsquares');
return {
'mapsquares': MapSquares.find({}, { 'sort': { 'row': 1, 'column': 1 } }).fetch(),
};
})(App));
```
查看文档: https://reacttraining.com/react-router/web/api/withRouter