简体   繁体   中英

ReactJs | Can not read property 'props' of undefined

I have app.js as the parent and uploadlist.js as the child. I am passing "userid" which is defined in app.js to uploadlist.js. This is my try:

app.js:

export default class App extends Component {

  state = {

    userrole : '',
    custid   : ''

  };

componentDidMount() {

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

}

render() {

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

uploadlist.js:

export default function Uploadlist() {
const userid = this.props.userid;
    console.log(userid);

This returns "TypeError: Cannot read property 'props' of undefined" error. How can I solve this?

Uploadlist is a functional component. It doesn't have this - rather, its props will be in the first parameter passed to the function, in the shape of an object.

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

or use a class component to reference this.props

export default class Uploadlist() {
  render() {
    console.log(this.props.userid);

when you want to pass props to the component rendered via Route use render prop instead of component .

Change your component as below

<Route path="/Uploadlist" render={props => <UploadList userid={props.match.params.userid} />}/>  

Also you are trying to access props.match.params.userid you won't have the userId here because you are rendering this component for the path /Uploadlist . But if the props.match is from a parent component which renders this Route then to avoid name collision change the name of your props as

render={routeProps => <UploadList userid={props.match.params.userid} {...routeProps} />}

Now you can access the props in your component as

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

Refer

Route Render Function

Route component Prop

UploadList is a functional component. Your route passes values top the component but when you defined UploadList, you did not accept any props as parameter.

It should be

function UploadList(props) {
.....
}
export default UploadList;

Or like @certainperformance answered, you could even use ES5 de-structuring to destructure the props parameter.

If you want to use 'this' use a class based component but that's a bit archaic and functional components are the best way to go for it these days

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