【问题标题】:Getting undefined props - React JS获取未定义的道具 - React JS
【发布时间】:2021-08-26 13:01:59
【问题描述】:

我正在使用 React JS 和 React Router。

我有 2 节课:

  1. App.js
  2. SomeClass.js

在 App.js 中:

class App extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            token: "",
            auth: false
        };
    }
    
    
    
    
    render(){

        return(
            <Router>
              
                <Switch>
                    <Route exact path="/anotherendpoint" component={() => <SomeOtherComponent auth={this.state.auth} token={this.state.token} />} />
                    <Route path="/someendpoint/abc" exact component={() => <SomeClass auth={this.state.auth} token={this.state.token} />} />
                </Switch>
            </Router>
            );
    }
    
}


export default App;

在 SomeClass.js 中:

class SomeClass extends React.Component{
    constructor(props){
        super(props);
    }
    
    
    logout = () =>{
        console.log('token: ', this.props.token);   //getting token: undefined
        let myCookie = document.cookie;
        console.log("cookie: ", myCookie);      //getting cookie: undefined
    }


}

export default Nav;

在 SomeClass 类中,每当我执行 this.props.token 时,我都会得到 undefined

当我使用 console.log(document.cookie) 时,我得到未定义

该问题仅出现在 SomeClass 组件中。这背后的原因是什么?

为什么道具是未定义的。

谢谢。

【问题讨论】:

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


    【解决方案1】:

    您将道具传递给组件的方式错误。只需像这样向组件添加道具:

    component={() => <SomeComponent auth={this.state.auth} token={this.state.token} />}
    

    【讨论】:

    • 什么是未定义的?
    • 什么是SomeClass?导航?
    【解决方案2】:

    试试这个方法。

    你可以在这里了解更多

    https://reactrouter.com/web/example/basic

        <Router>
          <Switch>
            <Route path="/teste" exact>
              <SomeOtherComponent auth="AUTH PROP" token="FAKE_TOKEN_PROP" />
            </Route>
          </Switch>
        </Router>

    【讨论】:

      猜你喜欢
      • 2020-01-06
      • 2016-11-08
      • 2018-04-18
      • 1970-01-01
      • 2021-02-12
      • 1970-01-01
      • 1970-01-01
      • 2022-06-30
      • 2018-04-15
      相关资源
      最近更新 更多