React-router-dom-链接更改URL但不呈现
我是React的新手,我已经<Link>
从dy数据中转到下一个或上一个项目(例如,如果我在user / 2视图上,则上一个链接转到user /
1,下一个链接转到user / 3 ),则正确更改了url,但完全不呈现该组件,并且根本不重新加载数据。
我读到这是由于组件未检测到子代未更改状态,所以父组件未呈现。
我尝试使用,withRouter
但出现错误:You should not use <Route> or withRouter() outside a
<Router>如果有人有解决方案并对此有一些解释,我不明白我在做什么,我将不胜感激:)
App.js:
import React, { Component } from 'react';import {
Route,
Switch,
withRouter,
} from 'react-router-dom';
import HomePage from './pages/home';
import SinglePage from './pages/single';
class App extends Component {
render() {
return (
<Switch>
<div>
<Route exact path="/" component={HomePage} />
<Route path="/:id" component={SinglePage} />
</div>
</Switch>
);
}
}
export default withRouter(App);
Single.js:
import React, { Component } from 'react';import Details from '../components/details'
import Header from '../components/header'
import { ProgressBar } from 'react-materialize';
class SinglePage extends Component {
constructor(props) {
super(props);
this.state = {
data: { data: null },
}
}
componentDidMount() {
fetch(`http://localhost:1337/${this.props.match.params.id}`)
.then((res) => res.json())
.then((json) => {
this.setState({
data: json,
});
});
}
render() {
const { data } = this.state;
return (
<div>
<h2> SinglePage </h2>
{!data ? (
<ProgressBar />
) : (
<div>
<Header id={this.props.match.params.id} />
<Details item={data} />
</div>
)}
</div>
);
}
}
export default SinglePage;
Header.js:
import React, { Component } from 'react';import PropTypes from 'prop-types';
import { Link, withRouter } from 'react-router-dom';
class Header extends Component {
static propTypes = {
item: PropTypes.shape({
data: PropTypes.string.isRequired,
}).isRequired,
}
render() {
const prev = parseInt(this.props.id) - 1
const next = parseInt(this.props.id) + 1
return (
<div>
<Link to="/"> Retour </Link>
<Link to={`/${prev}`}> Précédent </Link>
<Link to={`/${next}`}> Suivant </Link>
</div>
)
}
}
export default Header;
回答:
解决方案非常简单。您需要做的就是利用componentWillReceiveProps
并检查参数是否已更新,是否确实获取了数据
componentDidMount() { this.getData(this.props.match.params.id);
}
componentWillReceiveProps(nextProps) {
if(this.props.match.params.id !== nextProps.match.params.id) {
this.getData(nextProps.match.params.id);
}
}
getData = (param) => {
fetch(`http://localhost:1337/${params}`)
.then((res) => res.json())
.then((json) => {
this.setState({
data: json,
});
});
}
以上是 React-router-dom-链接更改URL但不呈现 的全部内容, 来源链接: utcz.com/qa/414101.html