我有一个代码,其中我使用react-router-dom v6进行路由
class App extends Component {
constructor(props) {
super(props);
this.state = {
accounts: [],
};
}
componentDidMount() {
getAccounts().then(r => this.setState({ // async req
accounts: r
}));
};
render() {
return (
<Routes>
<Route path="/" element={<AppLayout accounts={this.state.accounts} />}>
<Route index element={<Navigate to={`/account/1`} />}/>
<Route path="/account/:accountId" element={<TimelinePage/>}/>
<Route path="*" element={<NotFoundPage/>}/>
</Route>
</Routes>
);
}
}
我想从主页重定向到/accounts/${this.state.accounts[0]}
,但在装载应用程序组件之前,在异步请求之后,数组this.state.accounts
被填充,结果是,第一次渲染时,我得到了<NotFoundPage/>
.这是合乎逻辑的,但如何才能先获取异步数据,然后再重定向?
我提出了一个临时解决方案
<Route index element={<Navigate to={'/account/1'} />}/>`
但这并不能保证ID为1的元素始终存在于数组中
P.S.数组this.state.accounts
包含具有数字属性accountId
的对象.在<TimelinePage/>
组件中,我使用useParams()
获取帐户id,在<AppLayout/>
组件中,我渲染数组的每个元素