React Redux "Cannot read property 'props' of undefined"

70 views Asked by At

I'm pretty new to React and I created a simple game. I now decided to rebuild it and start using Redux. I use

{React.cloneElement(this.props.children, this.props)} in `Main.js`  

to pass props to first child which is World.js:

 Main.js
    (...)
    {React.cloneElement(this.props.children, this.props)} //props passed to World
    (...)
 export default Main;

then in World.js i pass props to Interface component:

World.js
   (...)
     <Interface
        {...this.props}
        /> 
   (...) 
export default World;

Finally, Interface.js is where the problem is. In getCurrentLocationfunction I'm trying to reach locations that is one of component props. It is available as prop to the component but in function it says "Cannot read property 'props' of undefined". The other thing is i had to change the sythax from

getCurrentLocation = (event) => {... to getCurrentLocation (event) {... in order it to work

Interface.js

class Interface extends React.Component {

    getCurrentLocation  (event)  { // Why is getCurrentLocation = (event) => ... not working?
      
        event.currentTarget.classList.add('active');
        const locationName = event.currentTarget.dataset.name;
    
        const updatedLocation={
            ...this.props.locations[locationName], //Line with error: Cannot read property 'props' of undefined
            isCurrentLocation: true,
        }
        (...)
         }
       };

render() {
 
return (
  (...)
)

Thanks to everyone interested.

1

There are 1 answers

0
Przemek On BEST ANSWER

Adding construtor like this fixed the issue

constructor(props) {
        super(props);

        this.getCurrentLocation = this.getCurrentLocation.bind(this);
        this.setCurrentLocation = this.props.setCurrentLocation.bind(this);
      }