简体   繁体   中英

Rest parameters produces an error in my react-bootstrap component?

This always works for me but for some reason, it does not work in my react-bootstrap component and this is confusing, rest parameter {classes, ...props} cause the code to throw an error and don't know why??

When i tried to reproduce the error in codesandbox everything worked ok, but the error still in my machine even after creating many new projects and removing all packages that can affect code till i reached to the point that i have created a very basic project i uploaded it on github here

Just importing the ReusableDropdown component from dropdown.js file produced a type error and react says that the error happens in the component itself not inside the parent component:

./src/reusable/dropdown.js
TypeError: Cannot read property 'forEach' of undefined

This should work and i am sure the error has no relation to the syntax, that's a kind of weird error!!

PS: You need to install react-bootstrap and bootstrap as dependencies to be able to reproduce the error

It could be an off-topic, but, since I saw there is no classes in <ReusableDropdown> component,

<ReusableDropdown text="his"/>

I want to suggest adding defaultProps like following

import React, { Component } from 'react';
import { Dropdown } from 'react-bootstrap';

export default ({classes = [], ...props}) => {
  return (
    <Dropdown>
       <Dropdown.Toggle className={classes.toggle}>{props.text}</Dropdown.Toggle>
       <Dropdown.Menu>
         <Dropdown.Item>hi</Dropdown.Item>
       </Dropdown.Menu>
    </Dropdown>
  );
}

Or, you can check null value

<Dropdown>
  <Dropdown.Toggle className={classes && classes.toggle}>
    {props.text}
  </Dropdown.Toggle>
  <Dropdown.Menu>
    <Dropdown.Item>hi</Dropdown.Item>
  </Dropdown.Menu>
</Dropdown>

And, I'm understanding that Dropdown.Toggle requires id prop. Could you check required props as well?

@Jaromanda X @Misol Goh Thanks for trying to help

after many hours trying to debug, i found this thread that answered my question

Cannot read property 'forEach' of undefined in React

Solution 1:

adding the following to package.json:

"resolutions": {
    "eslint-loader": "3.0.2"
  }

Solution 2:

downgrade to 3.0.1 version of react-scripts as the newer version caused that error for many users

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