首页 > 解决方案 > 在按钮 onClick 上使用 this.props.history 导航到另一个页面 reactJS

问题描述

运行此代码时,一切都会编译,但是当我单击“单击我”按钮而不是路由到“formPage.js”时,它会引发错误“TypeError:无法读取未定义的属性'push'”。我应该如何解决这个问题?

当我使用“www.google.com”而不是 formPage.js 时,它也会抛出同样的错误。

有没有办法解决这个问题而不必将我的整个代码转换为使用 useHistory() 的函数?

import axios from 'axios';
import React, { Component } from 'react';

export default class Form extends Component {

    constructor(props) {
        super(props);
        this.state = {
            message: []
        };
        this.handleClick = this.handleClick.bind(this);
    }

    async getData() {
        await axios.get("https://...")
        .then((response) => {
            const convertString = JSON.parse(response.data.body);
            this.setState({message: convertString});
        })
    }

    componentDidMount() {
        this.getData();
    }

    handleClick() {
        this.props.history.push("/formPage.js");
    }

    render() {
        const obj = (this.state.message);
        const datamapping = Object.entries(this.state.message);
        return (
            <div>
                <div className="viewall">
                    <table class="table table-hover">
                        <thead>
                            <th scope="col">Click me</th>
                            <th scope="col">key1</th>
                            <th scope="col">key2</th>
                        </thead>
                        <tbody>
                            {obj.Items?.map((data, key) => {
                                return (
                                    <tr key={key}>
                                        <td>
                                            <button type="button" class="btn btn-primary" onClick={this.handleClick}>
                                                Click me
                                            </button>
                                        </td>
                                        <td>{data.key1}</td>
                                        <td>{data.key2}</td>
                                    </tr>
                                )
                            })}
                        </tbody>
                    </table>
                </div>
            </div>
        );
    }
}

标签: reactjsreact-router

解决方案


推荐阅读