2016-05-01 42 views
6

我有一個範圍問題。我可以在構造函數中使用console.log this.props.routeParams.key。但是,當在構造函數之外,在filterList函數內,我得到錯誤「Uncaught TypeError:Can not read property'props'of undefined」。我的範圍問題是什麼?爲什麼它可以從構造函數中讀取,而不是從filterList函數中讀取?反應+反應路由器範圍界定

我正在使用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)} 
    } 
} 

回答

4

正在發生,因爲在你的構造你的filterList功能未綁定到您的組件

綁定它

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

你瞭解它here

+0

謝謝。這完全正確。你能解釋一下這背後的邏輯嗎? – CodeYogi

+1

正如我所說的,如果你沒有將函數綁定到你的組件,「this」將會是未定義的,因爲ES6類中沒有自動綁定。如果答案對你有幫助,你應該接受它。 – QoP

+0

我該如何接受它?我點擊了綠色的複選標記。你是這個意思嗎? – CodeYogi