简体   繁体   中英

How can I pass data from App.js to components?

I have App.js and a "uploadlist" functional component. I have defined a 'custid' in app.js and want to pass it to uploadlist component. Here is my try:

app.js:

export default class App extends Component {

  state = {

    userrole : '',
    userid   : ''

  };

componentDidMount() {

  if(localStorage.login)
  {
    const currentuser     = JSON.parse(atob(localStorage.login.split(".")[1])); 
    this.setState( {userrole: currentuser.role });
    this.setState( {userid: currentuser.id });
    
  }

}

render() {

if(this.state.userrole === "Customer"){
  const custid=this.state.userid;
  console.log(custid); //This properly returns the custid in console.
return (
//some code
<Route path="/Uploadlist" render={props => <UploadList custid={props.match.params.custid} />}/> 

uploadlist.js:

export default function Uploadlist({custid}) {
    console.log(custid);

This doesn't seems to be worked and returns undefined in the console. How is this to be solved? How to check if the custid is properly passed from app.js?

Do like this

<Route path="/Uploadlist" render={props => <UploadList custid={this.state.userid} />}/>

props.match.params.custid

This does not seem right to pass. Inside your App render component I would change custId={custId} because you create and assign that variable just above and you need to pass it to the component uploadlist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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