javascript - 我无法在 ReactJS 中正确使用 history.push()

标签 javascript reactjs

我是 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/

相关文章:

javascript - XML 格式错误 nunjucks 模板渲染

javascript - 将 child 居中到绝对全尺寸 parent

javascript - React中的setInterval更新状态但不识别时间何时为0

javascript - 从 Kendo Grid 过滤器中删除选项

javascript - 如何在用户将移动设备切换为横向时刷新网页

javascript - 在 Meteor.js 中, stub 的数据库写入是否总是在 stub 完成后立即完成?

reactjs - React 应用程序部署未定义 Netlify 环境变量

node.js - 无法在 Heroku 中查看 Express/React 应用程序(同时未找到)

javascript - 为javascript添加/删除文本多行

javascript - 在 Flatlist 项目中 react Native ref。仅返回最后一件商品