等待 react-router history.goBack 完成



我在一个索引数组状态的路由中。单击按钮时,我想删除状态外的项目。在执行此操作之前,我想返回到不使用该项目的另一条路线。我这样做是为了避免在索引不再存在的项目时出现 TypeError。

是否可以等待路由更改完成再更新状态?似乎没有使用历史记录的承诺功能。

最小示例:

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter, Switch, Route, useHistory } from 'react-router-dom'
class App extends Component {
constructor (props) {
super(props)
this.state = {
stuff: [{
message: 'hello'
}]
}
}
componentDidMount () {
console.log('mounted')
}
render () {
return (
<Switch>
<Route path='/1'>
<Child
stuff={this.state.stuff} callback={() => {
this.props.history.goBack()
this.setState({
stuff: []
})
}}
/>
</Route>
<Route path='/'>
<button onClick={() => this.props.history.push('/1')}>
Go to friend
</button>
home
</Route>
</Switch>
)
}
}
const Child = ({ callback, stuff }) =>
<>
<button onClick={callback}>
Go back
</button>
{stuff[0].message} friend
</>
const withUseHistory = (Component) => {
return function WrappedComponent (props) {
const history = useHistory()
return <Component {...props} history={history} />
}
}
const AppWithHistory = withUseHistory(App)
const wrapper = document.getElementById('root')
ReactDOM.render(
<BrowserRouter>
<AppWithHistory />
</BrowserRouter>,
wrapper)

我通过使用history.push而不是history.goBack找到了解决方案:

this.props.history.push('/')
this.setState({
stuff: []
})

似乎 history.push 是同步的,而 goBack 是异步的。

history.goBack();
// Register a popstate listener that executes only once during the next history entry change
window.addEventListener('popstate', onPopStateCallback, {once: true});

我们可以为下一个历史条目(弹出状态(更新注册一个回调

最新更新