我是 ReactJS 的初学者,我正在尝试使用 history.push()
重定向页面,但没有成功。谁能帮我说说我的代码有什么问题?我知道可以使用 React Router,但它对我正在尝试做的事情没有帮助。
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this)
}
handleClick(e) {
e.preventDefault()
this.props.history.push('/redirected');
}
render() {
return (
<div>
<button onClick={this.handleClick}>
Redirect!!!
</button>
</div>
)
}
}
export default App;
点击按钮后出现以下错误:
TypeError: Cannot read property 'push' of undefined
线上:
this.props.history.push('/redirected');
谢谢!
最佳答案
最简单的解决方案是:
安装历史:
npm install --save history
在 index.js 中初始化浏览器历史记录:
import { createBrowserHistory } from 'history';
export const browserHistory = createBrowserHistory();
使用:
browserHistory.push('/pathToRedirect')
关于javascript - 我无法在 ReactJS 中正确使用 history.push(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57778854/