reactjs - 反应路由器`this.props.history.push` - 历史未定义
问题描述
我有这个注销功能:
logOut = () => {
axios
.delete(`${apiUrl}/logout`)
.then(response => {
if (response.status === 204) {
localStorage.removeItem('key', response.headers.authorization)
localStorage.removeItem('id', response.data.id)
// return <Redirect to="/login" />
this.props.history.push(`/login`)
}
})
.catch(error => {
console.log(error)
})
}
this.props.history.push('/something')
适用于其他场合。但这里它说无法读取push
未定义。我试过return <Redirect to="/login" />
哪个也不起作用。
我究竟做错了什么?
解决方案
这可能是由于以下原因之一:
1-使用history.push时需要将组件传递给withRouter:
import { withRouter } from 'react-router-dom
// ... codes of component in here ...
export default withRouter(componentName) // at the end of component
2-这是指 axios,您需要在 axios 上用另一个名称定义它并在 axios 中使用它,例如:
var that = this;
// then use that in axios
推荐阅读
- python - 如何使用数字和星号符号创建矩形?
- java - JVM 够聪明吗?
- react-native - ScrollView中的FlatList不滚动
- node.js - Retrieve all Discord Channel IDs with matching names
- html - SVG not acting responsively despite being flexed and using relative units for resolution
- javascript - 获取 ForbiddenError:无效的 csrf 令牌(使用 firebase auth、autodesk forge 和 node.js)
- registry - SQL Server 2019 日志 - Polybase
- python - Discord py MemberNotFound 异常
- slack - 克隆现有的 Slack 应用程序
- json - 使用 where 条件更新 PostgreSQL 中的 jsonb 数据