反应动态路由器

时间:2017-08-24 15:25:50

标签: reactjs react-router

我怎样才能让这种动态变化?我目前有静态路由,但现在我需要一个可选的url参数

我想要实现的是拥有2个可选段,如此;

/users/{id}/{something}

'id'和'something'是可选参数

当我刚访问/用户时,它会转到用户列表

server.js

require('babel-register');

const express = require('express');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const { StaticRouter } = require('react-router-dom');
const lodash = require('lodash');
const fs = require('fs');
const baseTemplate = fs.readFileSync('./index.html');
const template = lodash.template(baseTemplate);
const App = require('../client/Root').default;
const port = 3000;

const server = express();

server.use('/public', express.static('./public'));

server.use(function (req, res) {
  const context = {};
  const body = ReactDOMServer.renderToString(
    React.createElement(
      StaticRouter, { location: req.url, context: context }, React.createElement(App)
    )
  );

  res.write(template({ content: body }));
  res.end();
})

server.listen(port, function () {
  console.log(`server running at port ${port}`)
});

在我的反应组件中

const Root = () => (
  <Provider store={store}>
    <Switch>
      <Route path='/users' exact component={Home}/>
    </Switch>
  </Provider>
)

2 个答案:

答案 0 :(得分:1)

您可以在react-router ...

中使用以下模式
<Route path="/users/:id" component={SomeComponent} />

然后您就可以访问id SomeComponent中的this.props.match.id作为export default { ... data () { return { bookList: [] } }, mounted: function() { this.$nextTick(function(){ this.viewBooks(); }); }, methods: { viewBooks: function() { axios.get('/books.json') .then(res=>{ this.bookList = res.data.bookList; }) .catch(error=>{ console.log(error); }); } }

答案 1 :(得分:0)

您可以嵌套路线。

const Root = () => (
  <Provider store={store}>
    <Switch>
      <Route path="/users" component={Home}>
        <IndexRoute component={YourDefaultComponent} />

        <Route path=":id/:something" component={YourOtherComponent} />
      </Route>
    </Switch>
  </Provider>
)