如何在React.js中实现动态页面?

时间:2019-02-13 19:37:54

标签: javascript node.js reactjs

import React, { Component } from "react";
import { FormattedMessage } from "react-intl";
import { connect } from "react-redux";

class Project extends Component {
  render() {
    return (
      <div
        className={
          "ih-item square effect6 from_top_and_bottom grid-item " +
          this.props.category +
          " " +
          this.props.widthClass
        }
      >
        <FormattedMessage id="route.project">
          {route => {
            return (
              <a href={"/" + route + this.props.url}>
                <div className="img">
                  <img src={this.props.mainImage} alt="img" />
                </div>
                <div className="info">
                  <h3>{this.props.header}</h3>
                  <p>{this.props.description}</p>
                </div>
              </a>
            );
          }}
        </FormattedMessage>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    projects: state.project.projects
  };
};

export default connect(
  mapStateToProps,
  {}
)(Project);

如何实现每个项目的页面和自定义URL。我想自定义URL必须用MongoDB完成,但是如何在reactjs中实现它。那是我研究的第三天,但大多数时候我发现了复杂的代码

感谢每个答案

2 个答案:

答案 0 :(得分:1)

我认为您需要安装react-router-dom。 其次,请使用template strings

答案 1 :(得分:1)

您很可能会使用React-Router之类的客户端导航软件包来完成此操作。

要设置基本路由器,您需要以以下方式定义路由和这些路由的视图,其中“路径”属性引用您所需的端点,“组件”为所需视图:

import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

const BasicExample = () => (
  <Router>
    <div>
     {/* Navigation menu */}
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
        <li>
          <Link to="/topics">Topics</Link>
        </li>
      </ul>

      <hr />
      {/* Routes */}
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/topics" component={Topics} />
    </div>
  </Router>
);

这些路由也可以使用路由数组动态生成,例如以下(在组件状态中定义):

routes = [
  {
    path: "/",
    exact: true,
    component: Home
  },
  {
    path: "/bubblegum",
    component: () => <div>bubblegum!</div>,

  },
  {
    path: "/shoelaces",
   component: Shoelaces
  }

,然后使用.map()在React中呈现:

{this.state.routes.map(route => (
  <Route exact={route.exact||false} path={route.path} component={route.component} />
))}