如何重定向到reactjs中的另一个页面。这是我的代码。
import React from 'react';
import { fade, makeStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import IconButton from '@material-ui/core/IconButton';
import Typography from '@material-ui/core/Typography';
import InputBase from '@material-ui/core/InputBase';
import Badge from '@material-ui/core/Badge';
import MenuItem from '@material-ui/core/MenuItem';
import Menu from '@material-ui/core/Menu';
import MenuIcon from '@material-ui/icons/Menu';
import SearchIcon from '@material-ui/icons/Search';
import AccountCircle from '@material-ui/icons/AccountCircle';
import MailIcon from '@material-ui/icons/Mail';
import NotificationsIcon from '@material-ui/icons/Notifications';
import MoreIcon from '@material-ui/icons/MoreVert';
export default function PrimarySearchAppBar() {
function logout(){
this.props.history.push({pathname:'/'})
}
}
每当我尝试将其sayas重定向为“ TypeError:无法读取未定义的属性'props'”
我该如何解决?
答案 0 :(得分:1)
您的组件应该看起来像这样
class PrimarySearchAppBar extends React.PureComponent {
logout = () => {
this.props.history.push({ pathname: '/' });
}
render() {
// some render logic here
return <button onClick={this.logout}>Logout</button>;
}
}
export default PrimarySearchAppBar;
或者具有这样的无状态组件
const logout = (props) => {
props.history.push({ pathname: '/' });
}
const PrimarySearchAppBar = (props) => {
// some render logic here
return <button onClick={() => logout(props)}>Logout</button>;
}
export default PrimarySearchAppBar;
请注意,对于无状态组件,您不能使用this
关键字,但必须像标准参数一样传递它。