如何使用普通路由定义配置react-router v3?

时间:2018-10-03 04:52:06

标签: javascript reactjs react-router

我正在尝试使用react-router v3来获得简单的路由定义,但是正如您从this Codesandbox所看到的,没有任何组件正在加载。

代码如下:

import Home from "/components/Home";
import About from "/components/About"; 

class App extends React.Component {
  render() {
    return <Router history={hashHistory} children={this.props.routes} />;
  }
}

let routes = {
  path: "/",
  childRoutes: [Home, About]
};

const root = document.getElementById("root");
ReactDOM.render(<App routes={routes} />, root);

我在这里真的缺少明显的东西吗?

以下是我正在使用的软件包(及其版本):

"react": "^15.6.2",
"react-dom": "^15.6.2",
"react-router": "^3.0.0",

2 个答案:

答案 0 :(得分:1)

首先,顶部的导入不正确。您应该使用relative路径来包含组件。
第二,要定义Routes结构,应使用<Route />组件。

我在这里对您的代码进行了一些更改:

import React from "react";
import ReactDOM from "react-dom";
import { hashHistory, Router, Route } from "react-router";

// components
import Home from "./components/Home";
import About from "./components/About";

class App extends React.Component {
  render() {
    const { routes } = this.props;

    return (
      <Router history={hashHistory}>
        {routes.childRoutes.map(({ Component, path }) => (
          <Route key={path} component={Component} path={path} />
        ))}
      </Router>
    );
  }
}

let routes = {
  path: "/",
  childRoutes: [
    {
      Component: Home,
      path: "home"
    },
    {
      Component: About,
      path: "about"
    }
  ]
};

const root = document.getElementById("root");
ReactDOM.render(<App routes={routes} />, root);

链接到沙盒https://codesandbox.io/s/6lvmry9pqk

页面:
https://6lvmry9pqk.codesandbox.io/#/home
https://6lvmry9pqk.codesandbox.io/#/about

答案 1 :(得分:0)

感谢伊万的回答!

结果证明该文档确实解释了how to do it,并且没有使用{{--@if(Auth::user()->id == $submission->id)--}} @if($task_submissions!== null ) @foreach($task_submissions as $task_submission) <object type="text/html" data="{{$task_submission->url}}" width="400px" height="350px" style="overflow:auto;border:5px ridge blue"> </object> @endforeach @else <p>No submissions</p> @endif {{--@endif--}} 就做到了。这是更新的代码:

.map()

Updated Codesandbox.