【问题标题】:React js TypeError: Cannot read properties of undefined (reading 'setState')React js TypeError:无法读取未定义的属性(读取 \'setState\')
【发布时间】:2022-11-17 12:20:48
【问题描述】:

所以我在使用 websockets 时为类组件设置状态时遇到问题。 picture of problem 看起来我的后端工作正常,问题出在前端。 我是新手,所以我不知道如何解决这里的问题。

数据“jsonBody”也提供了我们需要的正确信息。所以我想唯一的问题是为 this.state.users 列表设置状态。 前端代码:

class Users extends React.Component {

    // Constructor
    constructor(props) {
        super(props);
        this.state = {
            users: []
        }
        this.deleteUsers = this.deleteUsers.bind(this);
        this.editUsers = this.editUsers.bind(this);
        this.addUsers = this.addUsers.bind(this);

    }

    componentDidMount(){
        fetch("http://localhost:8080/users")
            .then(response => {
                return response.json()
            })
            .then(data => {
                this.setState({users: data})
            })
        const SOCKET_URL = 'ws://localhost:8080/ws-message';
        let onConnected = () => {
            console.log("Connected!!")
            client.subscribe('/topic/message', function (msg) {
                if (msg.body) {
                    var jsonBody = JSON.parse(msg.body);
                    this.setState({users: this.state.users.concat(jsonBody) });
                }
            });
        }
        let onDisconnected = () => {
            console.log("Disconnected!!")
        }
        const client = new Client({
            brokerURL: SOCKET_URL,
            reconnectDelay: 5000,
            heartbeatIncoming: 4000,
            heartbeatOutgoing: 4000,
            onConnect: onConnected,
            onDisconnect: onDisconnected
        });
        client.activate();
    }

    addUsers(user) {
        this.setState({users: this.state.users.concat(user) })
    }


    editUsers(user) {
        this.setState({users: this.state.users.map((users) => users.id === user.id ? user : users)})
    }


    deleteUsers(id){
        const api = "http://localhost:8080/users"
        axios.delete(api + "/" + id).then( res => {
            this.setState({users: this.state.users.filter(user => user.id !== id)});
        });
    }


    render() {

        return (
            <div className="container">
                <h1>Manage users</h1>
                <table className="table">
                    <thead>
                    <tr>
                        <th>name</th>
                        <th>username</th>
                        <th>email</th>
                        <th></th>
                    </tr>
                    </thead>
                    <tbody>
                    {this.state.users.map(user =>
                        <tr key={user.id}>
                            <td>{user.name}</td>
                            <td>{user.username}</td>
                            <td>{user.email}</td>
                            <td className="d-flex justify-content-end" ><Example user={user} users={this.state.users} editUsers={this.editUsers} ></Example>
                                <button className="remove btn btn-danger btn-sm  ms-3"  onClick={ () => this.deleteUsers(user.id)}>Remove</button>
                            </td>
                        </tr>
                    )}
                    </tbody>
                </table>
                <Example  users={this.state.users}  addUsers={this.addUsers} />
            </div >
        );
    }
}
export default Users;

后端:

   @PostMapping("/users")
    public List<User> addUsers(@RequestBody User user){
        UserDao.addUser(user);
        template.convertAndSend("/topic/message" ,user);
        return UserDao.showPostedUser();
    }

    @PutMapping("/users/{id}")
    public ResponseEntity<HttpStatus> editUsers(@PathVariable int id,@RequestBody User user){
        UserDao.updateUser(user,id);
        template.convertAndSend("/topic/update", UserDao.showUpdatedUser(id));
        return ResponseEntity.ok(HttpStatus.OK);
    }

    @DeleteMapping("/users/{id}")
    public ResponseEntity<HttpStatus> deleteUsersById(@PathVariable int id){
        UserDao.deleteUserById(id);
        template.convertAndSend("/topic/delete", id);
        return ResponseEntity.ok(HttpStatus.OK);
    }

    @SendTo("/topic/message")
    public User broadcastMessage(@Payload User user) {
        return user;
    }


    @SendTo("/topic/delete")
    public int broadcastDelete(@Payload int id) {
        return id;
    }

    @SendTo("/topic/update")
    public User broadcastUpdate(@Payload User user) {
        return user;
    }
}

【问题讨论】:

    标签: reactjs setstate


    【解决方案1】:

    箭头函数和函数不可互换。使用函数时,您会丢失组件的词法 this

                client.subscribe('/topic/message', (msg) => {
                    if (msg.body) {
                        var jsonBody = JSON.parse(msg.body);
                        this.setState({users: this.state.users.concat(jsonBody) });
                    }
                });
    

    【讨论】:

      猜你喜欢
      • 2020-07-10
      • 2021-12-09
      • 2017-05-30
      • 2017-10-30
      • 2021-03-16
      • 1970-01-01
      • 2022-12-21
      相关资源
      最近更新 更多