子组件无法访问通过React Route传递的道具

时间:2019-05-08 10:33:54

标签: javascript reactjs react-router bootstrap-material-design

我无法访问通过路线传递给子组件的道具。 我正在尝试获取App页面中的Authentication函数,以便当我在Login页面中的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访问测试道具,但没有成功。 知道我做错了吗?

3 个答案:

答案 0 :(得分:0)

尝试一下:

             <Route
              path="/login"
              render={props => <LoginPage test={this.state.isAuthenticated} {...props} />}
            />

您具有经过身份验证的身份而不是身份验证。

答案 1 :(得分:0)

您正在使用state来传递function作为道具,

<Route
   path="/login"
   render={props => <LoginPage test={this.state.Authentication} {...props} />} //Wrong way to pass function as prop
/>

如果您想通过function as prop,请使用Ref

<Route
   path="/login"
   render={props => <LoginPage test={this.Authentication} {...props} />}
/>

如果您想要multiple routes for same component,然后使用exact属性,请选中this

<Route 
  exact   //This will match exact path i.e. '/login'
  path="/login"
  render={props => <LoginPage test={this.Authentication} {...props} />}
/>

答案 2 :(得分:-1)

您的方法不是最佳实践。为此,最好使用redux + redux-thunk。

如果您仍然想这样走。 您在这里犯了错误:

 <Route
   path="/login"
   render={props => <LoginPage test={this.state.isAuthention} {...props} />}
 />

this.state.isAuthention替换为this.state.isAuthenticated 之后,您需要通过props身份验证回调发送并在fetch( ... ).then((result) => this.props.Authentication(result))

中进行调用