简体   繁体   English

如何将数据从 App.js 传递到组件?

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

I have App.js and a "uploadlist" functional component.我有 App.js 和一个“上传列表”功能组件。 I have defined a 'custid' in app.js and want to pass it to uploadlist component.我在 app.js 中定义了一个“custid”,并希望将其传递给 uploadlist 组件。 Here is my try:这是我的尝试:

app.js:应用程序.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:上传列表.js:

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

This doesn't seems to be worked and returns undefined in the console.这似乎不起作用并在控制台中返回 undefined 。 How is this to be solved?这要如何解决? How to check if the custid is properly passed from app.js?如何检查 custid 是否从 app.js 正确传递?

Do like this这样做

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

props.match.params.custid 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.在您的 App 渲染组件中,我将更改 custId={custId} 因为您在上面创建并分配了该变量,并且您需要将其传递给组件上传列表。

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

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