获取未定义的道具- React JS



我正在使用React JS和React Router。

我有两个类:

  1. App.js
  2. SomeClass.js
  3. 在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。令牌,得到undefined

当我输入console。log(document。cookie)时,我得到undefined

问题只发生在SomeClass组件中。这背后的原因是什么?

为什么道具没有定义

谢谢。

你以错误的方式传递props给组件。只需像这样为组件添加props:

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

试试这个方法。

你可以在这里了解更多

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

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

最新更新