【问题标题】:passing data from parent class to child class through props, but props not returning anything in child class通过道具将数据从父类传递到子类,但道具在子类中不返回任何内容
【发布时间】:2021-10-17 20:31:20
【问题描述】:

我正在使用 React JS。

我的父类 App.js,我的 Child 类是 SomeClass.js:

在我的 App.js 中,我有以下内容:

import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
class App extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            authaccount: {
                email: "",
                password: ""
            },
            authenticated: false
        };
    }
      render(){
        return(
            <Router>
        
              <Switch>
                <Route path="/somelink/abc" exact component={SomeClass} authenticated={this.state.authenticated} />
              </Switch>
            </Router>
        );
    
    }



}


export default App;

我还有另一个 React 组件:

class SomeClass extends React.Component{

    constructor(props){
        super(props);
        this.state = {
            item:[
                {
                    name: "",
                    material: "",
                },
            ],
        };
    }


    componentDidMount = () =>{
        if(this.props.authenticated === true && this.props.authaccount.email === "someemail@email.com") {
            this.someMethod();
        }else if(this.props.authenticated === true) {
            console.log(this.props.authaccount.email);   //getting undefined
            this.anotherMethod();
        }

    }

}
export default SomeClass;

App.js 是父类。 在我的 SomeClass 组件中,我想访问 App.js 状态中存在的“authaccount”的已验证属性和电子邮件属性

我的问题是如何将经过身份验证的值和电子邮件值从 App.js 传递给 SomeClass.js ?

我试图 console.log(this.props.authaccount.email); //但仍然未定义

【问题讨论】:

  • 你用SomeClass 吗?
  • "我试图 console.log(this.props.authaccount.email); //但没有得到任何数据" 你是否将属性传递给 App 组件中的 SomeClass 组件 像这样?
  • 我强烈推荐使用“react-router-dom”中的useHistory()钩子将props发送到不同的路由

标签: javascript reactjs react-redux react-router react-hooks


【解决方案1】:

你可以像这样传递道具:

 <Route path="/somelink/abc" exact component={() => (<SomeClass authenticated={this.state.authenticated} authaccount={this.state.authaccount} />)}  />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 2015-08-12
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多