因此,我对使用React进行编程非常陌生,并且在点击按钮后仍无法重定向到新页面。我正在使用react-hook-froms。
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import TextField from '@material-ui/core/TextField';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';
import { useForm } from 'react-hook-form'
import BoardService from '../service/BoardService';
import React, { useEffect, useState } from 'react';
import { useHistory } from 'react-router-dom';
const useStyles = makeStyles((theme) => ({
paper: {
marginTop: theme.spacing(40),
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.secondary.main,
},
form: {
width: '100%', // Fix IE 11 issue.
marginTop: theme.spacing(1),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
}));
export default function BoardName() {
useEffect(() => {
console.log("useEffect");
})
const [id, getId] = useState(1);
const history = useHistory();
const classes = useStyles();
const {register, handleSubmit} = useForm();
const onSubmit = (data) => {
let board = {
id: id,
name: data.boardName
}
console.log(board);
BoardService.createBoard(board.name, board);
history.push(`createboard/created`);
}
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Typography component="h1" variant="h5">
Name des Boards
</Typography>
<form className={classes.form} onSubmit={handleSubmit(onSubmit)} noValidate >
<TextField
variant="outlined"
margin="normal"
inputRef={register}
required
fullWidth
id="boardName"
label="Name"
name="boardName"
autoFocus
/>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
</form>
</div>
</Container>
);
}
history.push在onSubmit函数中不起作用,在浏览器中,我不断收到错误消息:未处理的拒绝(TypeError):无法读取未定义的属性“ push”。
我真的被困住了,无法继续前进。我很乐意提供任何帮助或建议。谢谢。
答案 0 :(得分:0)
使用react-router-dom软件包用BrowserRouter包装您的主索引文件
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById("root")
);
应该可以。