简体   繁体   English

在ReactJs中传递道具面临的问题

[英]Facing problems with passing down props in ReactJs

I'm having a hard time passing down props to a component. 我很难将道具传递给组件。 I want to be able to use that object in componentDidMount Method. 我希望能够在componentDidMount方法中使用该对象。 My current setup is i have an App component that is passing down an object to a Main which passes down that object as props to a TicketTable Component. 我当前的设置是我有一个App组件,该组件将对象向下传递到Main ,该对象作为道具传递给TicketTable组件。

This is my App component 这是我的App组件

 export default class App extends Component {


constructor(props) { 
super(props);
this.state= { 
  keycloak: null,
  authenticated: false,
  user : {}, role: ''
 }
}

componentDidMount() {
const keycloak = Keycloak('/keycloak.json');
    keycloak.init({onLoad: 'login-required'}).then(authenticated => {
        this.setState({ keycloak: keycloak, authenticated: authenticated});
        // this.state.keycloak.loadUserInfo().success(user => this.setState({user}));
    }).catch(err=>console.log("ERROR", err));
 }
   render() {
return (

  <div>
      <Main keycloak={this.state.keycloak}/>

This is my Main component 这是我的主要组成部分

export default class Main extends Component {
constructor(props){
  super(props);
 this.state={keycloak:''}
}

componentDidMount(){
  console.log("MAIN PROPS",this.props);
}


}
 render() {
     return (
       <div>
        <Switch>
           <Route exact path="/" render={(props)=><TicketTable 
  {...props} keycloak={this.state.keycloak}/>}/>

I want to to able to use the Keycloak object in my TicketTable component. 我希望能够在TicketTable组件中使用Keycloak对象。

Thank you. 谢谢。 Ps: I want to able to do that without the need of using a state management framework like redux 附言:我希望能够做到这一点,而无需使用像redux这样的状态管理框架

The keycloak prop that you are passing to your TicketTable component is actually empty because you are passing the state of the Route component as the prop and not the one which you got from App component. 传递给TicketTable组件的keycloak道具实际上是空的,因为传递的是Route组件的状态作为道具,而不是从App组件获得的状态。

So make this change and I think it should work: 因此,进行此更改,我认为它应该起作用:

<Route exact path="/" render={(props)=><TicketTable 
{...props} keycloak={this.props.keycloak}/>}/>

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

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