反应路由器链接按钮不与路由器?

时间:2019-01-09 02:30:14

标签: javascript reactjs react-router

我有一个非常简单的react应用。

在主要的App.js中,我有一个Router及其路线。

在生活在PostItem中的另一个独立组件MainComponent中,我有一个Link按钮指向另一个组件JobPost

我不断得到:

Cannot GET /job/7

此设置有效吗?还是我的Router组件中需要有一个Link元素?

App.js:

import React from 'react';
import { render } from 'react-dom';
import MainComponent from './index.js';
import JobPost from './components/JobPost.js';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";


const App = () => (
  <Router>
    <div>
      <Route path="/" exact component={MainComponent} />
      <Route path="/job/:id" exact component={JobPost} />
    </div>
  </Router>
);

render(<App />, document.getElementById('root'));

PostItem.js:

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

export default function PostItem(props){
  return(
    <div className="post-item">
    <div className="job-details">
      <h2 className="job-title" dangerouslySetInnerHTML={{__html:  props.title  }} />
      <h3 className="job-location"> Test Company - <i>Test Location</i></h3>
      <div className="job-description">
      <span dangerouslySetInnerHTML={{__html:  props.content  }} />
      </div>
    </div>
    <button className="view-btn">
      <Link to={ `/job/` + props.id } >
        View
      </Link>
      </button>
    </div>
  );
}

JobPost.js:

import React, { Component } from 'react';

//make actual class and render again

export default class JobPost extends Component{
    constructor(props){
      super(props);
      this.state={
        id: this.props.match.params.id
      };
    }

    componentDidMount(){
      //fetch id from component
      console.log(this.state.id);
    }

    render(){
      return(
      <div className="post-container">
      <div className="job-details">
        <h2 className="job-title" dangerouslySetInnerHTML={{__html:  props.title  }} />
        <h3 className="job-location"> Test Company - <i>Test Location</i></h3>
        <div className="job-description">
        <span dangerouslySetInnerHTML={{__html:  props.content  }} />
        </div>
      </div>
      <button className="apply-btn">Apply</button>
      </div>
    );
  }
}

0 个答案:

没有答案