我想点击按钮登录时更改我的页面,但出现错误:无法读取属性'推送'未定义的。 如何更正代码?
这是我的登录文件:
import React from 'react';
import CreateUser from "./CreateUser";
import GetUser from "./GetUser";
import { BrowserRouter as Router, Link, Route} from 'react-router-dom';
import Routes from "./Routes";
export default class Login extends React.Component { //create Login class and export
state = { // for hold all the values
email: '',
password: '',
};
change = e => {
this.setState({
[e.target.name]: e.target.value //grab name value and put here
});
};
onSubmit = (e) => {
e.preventDefault(); //avoid url change because of values
this.props.onSubmit(this.state);
this.props.history.push("/GetUser");
this.setState({
email: '',
password: '',
})
};
//create a form
render() {
return (
<form>
<br / /*line breaks*/>
Login
<br />
<br />
<input
name="email"
placeholder='email' //appears in the field to write
value={this.state.email} //input value
onChange={e => this.change(e)} //allow change the value by typing
/>
<br />
<br />
<input
name="password"
type='password' //hidden password type
placeholder='password'
value={this.state.password}
onChange={e => this.change(e)}
/>
<br/ >
<br/ >
<button onClick={e => this.onSubmit(e)} /*Login button*/>Login</ button>
<br/ >
<br/ >
<button onClick={e => this.onSubmit(e)}/*Sign Up button*/>Sign Up</button>
</form>
);
}
}
这是我的路线档案:
import React from 'react';
import { Router, Route } from 'react-router';
import App from './App';
import Login from './Login';
import CreateUser from './CreateUser';
import GetUser from './GetUser'
const Routes = (props) => (
<Router {...props}>
<Route exact path="/GetUser" component={GetUser}/>
<Route exact path="/CreateUser" component={CreateUser}/>
</Router>
);
export default Routes;
我是React的新手,真的需要帮助。我想在点击按钮后访问GetUser文件。
总而言之, 爱德华多·格里斯
答案 0 :(得分:9)
要在组件中使用history
对象,您需要使用withRouter
中的react-router-dom
HOC。例如:
import React from "react";
import {withRouter} from "react-router-dom";
class Login extends React.Component {
...
onSubmit() {
...
this.props.history.push("/GetUser");
}
...
}
export default withRouter(Login);