响应路由与URL参数不更新视图

我有一个反应观点/wiki/:artical 。 当我从一个不同的视angular去维基(例如从//wiki/some-artiacal )我的观点更新,但是当我从一个维基到另一/wiki/some-artiacal (例如/wiki/some-artiacal/wiki/some-other-artiacal )页面不会与新的内容。 看来React认为它们是相同的观点,并且不会重新渲染页面。 如果我手动刷新浏览器,文章更新,但是当我点击<Link to='/wiki/some-other-artiacal'></Link>时,我想要刷新。

反应路由器文件:

 import React from "react"; import ReactDOM from "react-dom"; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; // COMPONENTS import Header from './components/Header'; // VIEWS import HomePage from './views/HomePage'; import WikiPage from './views/WikiPage'; import ProblemTesterPage from './views/ProblemTesterPage'; import NoMatchPage from './views/NoMatchPage'; ReactDOM.render( <Router> <div className='container-fluid'> <div className='row justify-content-center'> <div className='col-xs-12 col-lg-8'> <Header/> <div className='card'> <div className='card-body'> <Switch> <Route exact={true} path='/' component={HomePage}></Route> <Route exact={true} path='/wiki/:artical' component={WikiPage}></Route> <Route exact={true} path='/tools/problem-tester' component={ProblemTesterPage}></Route> <Route component={NoMatchPage}/> </Switch> </div> </div> <p className='footer text-center text-secondary'>©2017 MathBrainius</p> </div> </div> </div> </Router> , document.getElementById('app')); 

Wiki组件:

 import React from 'react'; import ReactMarkdown from 'react-markdown'; export default class HomePage extends React.Component { constructor(props) { super(props); this.state = { artical: '' }; } componentDidMount() { var s = this; var props = s.props; axios.get(`/api/wiki/${props.match.params.artical}`, { timeout: 20000, }) .then(res => { var ping = res.data; s.setState({ artical: ping.artical }); }); } render() { var s = this; return ( <div> <ReactMarkdown source={s.state.artical}/> </div> ) } } 

您的组件不重新安装,只是接收新的道具,所以你可以使用componentWillReceiveProps钩子:

 ... loadData(article) { var s = this axios.get(`/api/wiki/${article}`, { timeout: 20000, }) .then(res => { var ping = res.data; s.setState({ artical: ping.artical }) }) } componentDidMount() { this.loadData(this.props.match.params.artical) } componentWillReceiveProps(nextProps) { this.loadData(nextProps.match.params.artical) } ...