在同一级别切换路由时,正确的数据获取方式是什么?
因为根据this,相同级别的交换路由将
仅调用componentWillReceiveProps
和componentDidUpdate
。
而componentDidMount
仅在第一次输入路径时被称为。
使用这样的路由配置:
render((
<Provider store={store}>
<Router>
<Route path="/" component={App}>
<Route path="/:userId" component={Profile}/>
</Route>
</Router>
</Provider>
), document.getElementById('root'));
配置文件组件是:
class Profile extends React.Component {
componentDidMount() {
// initial data
this.fetchUserData();
}
componentWillReceiveProps(nextProps) {
if (this.props.params.userId !== nextProps.params.userId) {
this.fetchUserData();
}
}
shouldComponentUpdate(nextProps) {
return this.props.params.userId !== nextProps.params.userId;
}
render() {
return (
<div className="profile"></div>
);
}
}
数据将存储在应用程序状态字段(
props.userData
)中。但,这显然会弄乱渲染周期,因为route是
在获取数据完成之前切换。
但是,如果我更改为:
// deepEqual is function to check object equality recursively
componentWillReceiveProps(nextProps) {
if (!deepEqual(this.props.userData, nextProps.userData)) {
this.fetchUserData();
}
}
shouldComponentUpdate(nextProps) {
return !deepEqual(this.props.userData, nextProps.userData);
}
这是行不通的,因为在获取
userData
之前,这些道具是非常平等。
那么,在同一路由级别切换路由时如何获取数据?
最佳答案
componentDidMount () {
// fetch data initially in scenario 2 from above
this.fetchInvoice()
},
componentDidUpdate (prevProps) {
// respond to parameter change in scenario 3
let oldId = prevProps.params.invoiceId
let newId = this.props.params.invoiceId
if (newId !== oldId)
this.fetchInvoice()
},
更改路线时,
this.props.params.userId
将更新,该更新将捕获在componentDidUpdate中,并触发获取。当然,此获取可能会更新状态或道具触发另一个重新渲染以显示获取的数据。关于javascript - 在React-Router中在同一级别上切换路由时获取数据的正确方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37627648/