2016-05-01 41 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