无法读取未定义的属性(读取‘navigate’)
2022-07-21
1227
登录成功后,我正在处理路由。但是出现了这个错误:
Uncaught TypeError: Cannot read properties of undefined (reading 'navigate')
这是登录页面
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
loginName: "",
password: "",
loginNameError: null,
passwordError: null,
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
this.props.navigation.navigate("/employee")
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div className="input-container">
<label>User ID</label>
<input type="text" name="loginName" value={this.state.loginName} onChange={(e) => (this.setState({ loginName: e.target.value }))} />
<p>{this.state.loginNameError}</p>
</div>
<div className="input-container">
<label>Password</label>
<input type="password" name="password" value={this.state.password} onChange={(e) => (this.setState({ password: e.target.value }))} />
<p>{this.state.passwordError}</p>
</div>
<div className="button-container"><input type="submit" value="CONNECT"></input></div>
</form>
);
}
}
export default Login;
这是APP.js
function App() {
return (
<div class="page">
<BrowserRouter>
<Routes>
<Route path="/employee" element={<UserManagement />}></Route>
<Route path="/login" element={<Login />}></Route>
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
如何解决这个错误?
2个回答
Since react router v6 doesnt have withRouter
// https://reactrouter.com/docs/en/v6/getting-started/faq#what-happened-to-withrouter-i-need-it
import {
useLocation,
useNavigate,
useParams,
} from "react-router-dom";
function withRouter(Component) {
function ComponentWithRouterProp(props) {
let location = useLocation();
let navigate = useNavigate();
let params = useParams();
return (
<Component
{...props}
router={{ location, navigate, params }}
/>
);
}
return ComponentWithRouterProp;
}
// then in the Login class component you can consume withRouter
handleSubmit(event) {
event.preventDefault();
// consume `router` prop
this.props.router.navigate("/employee");
}
// Wrap Login in withRouter HOC to make sure `router` prop is available
export default withRouter(Login);
// export default Login;
话虽如此,我建议使用带有函数组件的 react-router,而不是类组件。
alextrastero
2022-07-21
因为使用类组件,所以不能使用钩子! 但我认为这在这里有效:
this.props.history.push("/employee");
Arash Ghazi
2022-07-21