[英]React Route with URL Param Not Updating View
我有一個反應視圖/wiki/:artical
。 當我從另一個視圖轉到Wiki(例如,從/
到/wiki/some-artiacal
)時,我的視圖會更新,但是當我從一個wiki文章轉到另一個(例如, /wiki/some-artiacal
到/wiki/some-other-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)
}
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.