简体   繁体   English

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

[英]Props passed through React Route cant be accessed by child component

I am having a problem accessing the props passed through the route to the child component. 我在访问通过路由到达子组件的道具时遇到问题。 I am trying to get hold of the Authentication function in the App page , so that I can toggle it to true when my onLogin function in the Login page get the correct response. 我正在尝试获取App页面中的Authentication函数,以便当我在Login页面中的onLogin函数获得正确的响应时,可以将其切换为true。 Any help will be highly appreciated. 任何帮助将不胜感激。

please find the code below 请在下面找到代码

//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;

I am trying to access the test prop from the loginPage but no success. 我正在尝试从loginPage访问测试道具,但没有成功。 Any idea were am I going wrong? 知道我出了错吗?

Try this: 尝试这个:

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

You have isAuthenticated not Authentication. 您具有isAuthenticated而不是Authentication。

Your approach is not the best practice. 您的方法不是最佳做法。 For such purposes it is best to use redux + redux-thunk. 为此,最好使用redux + redux-thunk。

If you still want to go this way. 如果您仍然想这样走。 You make mistake on here: 您在这里犯了错误:

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

this.state.isAuthention replace on this.state.isAuthenticated After that you need send via props Authentication callback and call it's in fetch( ... ).then((result) => this.props.Authentication(result)) this.state.isAuthention替换this.state.isAuthenticated之后,您需要通过props发送身份验证回调,并在fetch( ... ).then((result) => this.props.Authentication(result))调用它fetch( ... ).then((result) => this.props.Authentication(result))

You are using state to pass function as prop, 您正在使用statefunction作为道具传递,

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

If you want to pass a function as prop use this, Ref 如果您想将function as prop传递function as prop使用Ref

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

If you want multiple routes for same component , then use exact attribute like this, check this 如果您希望multiple routes for same component ,则使用exact一样的属性,请检查

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM