我在访问通过路由传递到子组件的道具时遇到问题。我正在尝试获取 App 页面中的 Authentication 功能,以便在登录页面中的 onLogin 功能获得正确响应时将其切换为 true。任何帮助将不胜感激。
请在下面找到代码
//App.js
import React, { Component } from "react";
//import TopNavigation from './components/topNavigation';
//import { BrowserRouter, Route, Switch } from "react-router-dom";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import MainPage from "./Mainpage";
import LoginPage from "./components/pages/LoginPage";
//import ProtectedRoute from "./protected.route";
import "./styleFiles/index.css";
class App extends Component {
constructor() {
super();
this.state = {
isAuthenticated: false
};
this.Authentication = this.Authentication.bind(this);
}
Authentication(e) {
this.setState({ isAuthenticated: e });
}
render() {
if (this.state.isAuthenticated === false) {
return (
<BrowserRouter>
<div className="flexible-content ">
<Route
path="/login"
render={props => <LoginPage test="helloworld" {...props} />}
/>
<Route component={LoginPage} />
</div>
</BrowserRouter>
);
} else {
return (
<div className="flexible-content ">
<Switch>
<Route
path="/"
exact
component={MainPage}
/>
<Route component={MainPage} />
</Switch>
</div>
);
}
}
}
export default App;
//login page
import React, { Component } from "react";
import logo from "../../assets/justLogo.svg";
import "../../styleFiles/loginCss.css";
class LoginPage extends Component {
constructor(props) {
super(props);
}
onLogin = event => {
let reqBody = {
email: "rpser1234@gmail.com",
password: "rpser1234"
};
// event.preventDefault();
fetch("http://localhost:8000/api/auth/login", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(reqBody)
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw new Error("Something went wrong with your fetch");
}
})
.then(json => {
localStorage.setItem("jwtToken", json.token);
console.log(this.props.test);
});
};
render() {
const {
test,
match: { params }
} = this.props;
console.log(test);
return (
<div className="bodybg">
<div className="login-form">
<div className="form-header">
<div className="user-logo">
<img alt="MDB React Logo" className="img-fluid" src={logo} />
</div>
<div className="title">Login</div>
</div>
<div className="form-container">
<div className="form-element">
<label className="fa fa-user" />
<input type="text" id="login-username" placeholder="Username" />
</div>
<div className="form-element">
<label className="fa fa-key" />
<input type="text" id="login-password" placeholder="Password" />
</div>
<div className="form-element">
<button onClick={this.onVerify}>verify</button>
</div>
<div className="form-element forgot-link">
<a href="http://www.google.com">Forgot password?</a>
</div>
<div className="form-element">
<button onClick={this.onLogin}>login</button>
</div>
</div>
</div>
</div>
);
}
}
export default LoginPage;
我正在尝试从 loginPage 访问测试道具,但没有成功。知道我错了吗?