我有一个非常简单的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>
);
}
}