Scoping in React + React Router
Asked Answered
D

1

7

I am having a scoping issue. I can console.log this.props.routeParams.key from within the constructor. But when outside of the constructor, within the filterList function, I get the error "Uncaught TypeError: Cannot read property 'props' of undefined". What's my scoping issue? Why can it read the this from within the constructor but not from within the filterList function?

I am using React Router + Flux + React.

import AltContainer from 'alt-container';
import React from 'react';
import { Link } from 'react-router';
import Blogger from './Blogger'
import List from './List'
const rootURL = 'https://incandescent-fire-6143.firebaseio.com/';

import BlogStore from '../stores/BlogStore'
import BlogActions from '../actions/BlogActions';


export default class BlogShow extends React.Component {
  constructor(props) {
    super(props);
    {console.log(this.props.routeParams.key)}
}


filterList(key) {
  if (this.props.routeParams.key===key){
    return Blogstore.state.blog
  }
}

  render() {
             {Object.keys(BlogStore.state.blog).map(this.filterList)}
  }
}
Dilisio answered 1/5, 2016 at 14:35 Comment(0)
T
5

that is happening because your filterList function is not bound to your component

Bind it in your constructor

constructor(props) {
    super(props);
    this.filterList = this.filterList.bind(this);
}

You read about it here

Triplet answered 1/5, 2016 at 14:42 Comment(4)
Thank you. This is exactly correct. Can you please explain the logic behind this?Dilisio
as I said, if you don't bind the function to your component, "this" is going to be undefined because there is no autobinding in ES6 classes. If the answer helped you, you should accept it.Triplet
Yeah, you should do that when an answer solves your problem :P meta.stackexchange.com/questions/5234/…Triplet
Thank you for your help!Dilisio

© 2022 - 2024 — McMap. All rights reserved.