首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >“withRouter”已导入,但仍获取推送:无法读取未定义的属性“TypeError”

“withRouter”已导入,但仍获取推送:无法读取未定义的属性“TypeError”
EN

Stack Overflow用户
提问于 2019-10-13 05:02:51
回答 2查看 112关注 0票数 1

下面是我用于添加用户的组件代码。

代码语言:javascript
运行
复制
import React, { Component } from 'react';
import UserDataService from '../service/UserDataService';
import { withRouter} from 'react-router-dom';

class ListUsersComponent extends Component {

    constructor(props) {
        super(props)
        this.state = {
            users: [], 
            message: null
        }
        this.refreshUsers = this.refreshUsers.bind(this)
        this.deleteUserClicked = this.deleteUserClicked.bind(this)
        this.addUserClicked = this.addUserClicked.bind(this)
        this.createUser = this.createUser.bind(this)
    }

    componentDidMount() {
        this.refreshUsers()
    }

    refreshUsers() {
        UserDataService.retrieveAllUsers()
            .then(
                response => {
                    console.log(response)
                    this.setState({ users: response.data })
                }
            )
    }

    deleteUserClicked(id) {
        UserDataService.deleteUser(id)
            .then(
                response => {
                    this.setState({ message: `Delete of ${id} Successful` })
                    this.refreshUsers()
                }
            )
    }

    addUserClicked() {
        this.props.history.push(`/courses/-1`)
    }

    createUser(user) {
        UserDataService.addUser(user)
            .then(
                response => {
                    this.setState({ message: `User ${user.firstName} ${user.lastName} Successfully added`})
                    this.refreshUsers()
                }
            )
    }

    render() {
        return (
            <div className="container">
                <h3> All Users </h3>
                {this.state.message && <div class="alert alert-success">{this.state.message}</div>}
                <div className="container">
                    <table className="table">
                        <thead>
                            <tr>
                                <th>Id</th>
                                <th>FirstName</th>
                                <th>LastName</th>
                                <th>Email</th>
                                <th></th>
                                <th></th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            {
                                this.state.users.map(
                                    user =>
                                        <tr key={user.id} >
                                            <td>{user.id}</td>
                                            <td>{user.firstName}</td>
                                            <td>{user.lastName}</td>
                                            <td>{user.email}</td>
                                            <td>
                                                <img src={user.imagePath}></img>
                                            </td>
                                            <td>
                                                <button className="btn btn-warning" onClick={() => this.deleteUserClicked(user.id)}>Delete</button>
                                            </td>
                                            <td>
                                                <button className="btn btn-success" onClick={() => this.updateUserClicked(user.id)}>Update</button>
                                            </td>
                                        </tr>
                                )
                            }
                        </tbody>
                    </table>
                </div>
                <div className="row">
                    <button className="btn btn-success" onClick={this.addUserClicked}>Add</button>
                </div>
            </div>
        )
    }
}

export default ListUsersComponent

使用简单的按钮html

代码语言:javascript
运行
复制
 <div className="row">
    <button className="btn btn-success" onClick={this.addUserClicked}>Add</button>
 </div>

但是当我点击add按钮时,我会看到

代码语言:javascript
运行
复制
TypeError: Cannot read property 'push' of undefined
ListUsersComponent.addUserClicked
http://localhost:3000/static/js/main.chunk.js:188:24
  185 | }
  186 | 
  187 | addUserClicked() {
> 188 |   this.props.history.push("/user/-1");
      |                      ^  189 | }

这里我漏掉了什么?我非常确定我所有的版本都是最新的。我已经根据要求发布了ListUsersComponent的所有代码。我必须键入更多的信息,因为我现在有太多的代码。是否有任何其他需要帮助评估我的问题

这是我要求的控制器

代码语言:javascript
运行
复制
    private UserRepository repo;

    @GetMapping("/users")
    public Iterable<User> getAllUsers() {
        return repo.findAll();
    }

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable Long id) {
        Optional<User> user = repo.findById(id);
        if (user == null) {
            ResponseEntity.notFound().build();
            return null;
        }

        ResponseEntity.noContent().build();
        return user.get();
    }
EN

回答 2

Stack Overflow用户

发布于 2019-10-13 05:18:40

withRouter是一个更高阶的组件,它不能仅仅通过导入它来工作。

实际上,您需要将组件包装在withRouter中才能访问this.props.history

代码语言:javascript
运行
复制
export default withRouter(ListUsersComponent);

您还需要用Router包装App

代码语言:javascript
运行
复制
import { Router } from "react-router";
import { createBrowserHistory } from "history";

const history = createBrowserHistory();

ReactDOM.render(
  <Router history={history}>
    <App />
  </Router>,
  document.getElementById('root')
)
票数 2
EN

Stack Overflow用户

发布于 2019-10-13 05:22:43

Read Docs

您可以通过withRouter高阶组件访问历史对象的属性和最接近的匹配项。每当withRouter呈现时,它都会将更新的匹配项、位置和历史属性传递给包装组件。

要使属性在组件中可用,除了导入函数外,还必须调用withRouter(Component)

在你的情况下,

代码语言:javascript
运行
复制
export default withRouter(ListUsersComponent);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58358484

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档