简体   繁体   中英

TypeError: undefined is not an object (evaluating 'this.props.history.push')

I am facing a problem that my this.props return {} , which is empty. But it suppose to be a room code.

RoomJoinPage.js

import React, { Component } from  'react';
import HomePage from './HomePage';
import 
{ 
    Button, 
    Grid, 
    Typography, 
    TextField,
    FormHelperText,
    FormControl,
    Radio,
    RadioGroup,
    FormControlLabel
} from '@mui/material';
import { Link } from 'react-router-dom';

export default class RoomJoinPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            roomCode: "",
            error: "",
        };
        this._handleTextFieldChange = this._handleTextFieldChange.bind(this);
        this.roomButtonPress = this.roomButtonPress.bind(this);
    }
    render() {
        return (
            <Grid container spacing={ 1 }>
                
                <Grid item xs={12} align="center" >
                    <Typography variant='h4' component="h4">
                        Join a Room
                    </Typography>
                </Grid>
                <Grid item xs={12} align="center">
                    <TextField 
                    error= {this.state.error}
                    label="Code"
                    placeholder="Enter a room code"
                    value= {this.state.roomCode}
                    helperText= {this.state.error}
                    variant="outlined"
                    onChange={this._handleTextFieldChange}
                    />
                </Grid>

                <Grid
                container
                spacing={1}
                style={{width: "100", padding: 10}}
                direction="column"
                alignItems="center"
                justifyContent="center"
                alignContent="center"
                >
                
                    <Grid item  xs={12}>
                        <Button variant='contained' color='secondary' onClick={this.roomButtonPress}>Enter room</Button>
                    </Grid>
                    <Grid item xs={12}>
                        <Button variant='contained' color='primary' to='/' component={Link}>Back</Button>
                    </Grid>
                </Grid>
            </Grid>
        );
    }
    _handleTextFieldChange(e) {
        this.setState({
            roomCode: e.target.value,
        });
    }

    roomButtonPress(e) {
        const requestOptions = {
            method: "POST",
            headers: {"Content-Type": "application/json" },
            body: JSON.stringify({
                code: this.state.roomCode
            })
        };
        console.log(this.props)
        fetch('/api/join-room', requestOptions)
        .then((response) => {
            if (response.ok) {
                this.props.history.push(`/room/${this.state.roomCode}`)
            }
            else {
                this.setState({error: "Room not found."})
            }
        })
        .catch((error) => {
            console.log(error); 
        });
    }
}

The problem should be in the roomButtonPress function. I am new to react, how can I pass the this.props to that function?

The expected result is, when I click the Enter Room button with the correct room code (connected to Django backend), it should redirect to the room page, /room/roomCode

I used RoomJoinPage in HomePage.js

import React, { Component } from  'react';
import RoomJoinPage from './RoomJoinPage';
import CreateRoomPage from './CreateRoomPage';
import Room from './Room';
import { BrowserRouter as Router, Routes, Route, Link, Redirect } from 'react-router-dom';

export default class HomePage extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
         <Router>
            <Routes>
                <Route exact path='/' element={<p> <h1>This is the home page</h1>
                    <a href='./join'> Link to room join page </a>
                    <br/><a href='./create'> Link to room create page </a>
                    <br/><a href='./api/home'> API? </a>
                    </p>}></Route>
                <Route exact path='/join' element={<RoomJoinPage></RoomJoinPage>}></Route>
                <Route exact path='/create' element={<CreateRoomPage></CreateRoomPage>}></Route>
                <Route exact path='/room/:roomCode' element={<Room></Room>}></Route>
            </Routes>
         </Router>   
        );
    }
}

Looks like you havent integrated React Router in page.

Try these changes in RoomJoinPage.js

Include withRouter

import { withRouter } from "react-router";

Change

 export default class RoomJoinPage extends Component {

to

 class RoomJoinPage extends Component {

End of the page, export component with withRouter

 const NewRoomJoinPage = withRouter(RoomJoinPage);
 export default NewRoomJoinPage;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM