gpt4 book ai didi

javascript - react 路线与 URL 参数不更新 View

转载 作者:行者123 更新时间:2023-11-30 15:00:01 25 4
gpt4 key购买 nike

我有一个 react View /wiki/:artical .当我从不同的 View 转到维基时(例如从 //wiki/some-artiacal )我的 View 更新,但是当我从一个维基文章转到另一个(例如 /wiki/some-artiacal/wiki/some-other-artiacal )页面不会重新呈现与新内容。似乎 React 将它们视为相同的 View 并且不会重新呈现页面。如果我手动刷新浏览器,文章会更新,但我想在单击 <Link to='/wiki/some-other-artiacal'></Link> 时做出刷新 react .

react 路由器文件:

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'));

维基组件:

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>
)
}
}

最佳答案

您的组件没有重新安装,只是接收新的 Prop ,因此您可以使用 componentWillReceiveProps Hook :

...

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)
}

...

关于javascript - react 路线与 URL 参数不更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46694434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com