2015-07-20 2 views
1

Я новичок на всю экосистему, и я удивляюсь, почему в моем примере компоненте внутри визуализации функции this.state.displayedListItems представляет собой массив строк, как и ожидалась, но внутри функций filterList this.state.displayedListItems не определен?TSX и государственные различия членов

Я использую

Atom 1.0.2 (https://atom.io/) 
atom-typescript 5.0.29 (https://github.com/TypeStrong/atom-typescript), 

tsd 0.6.3 with 
"react/react.d.ts": { "commit": "a9c59f8166b4d7f1e8c4309a506987c2e6d78b5e"}, 
"react/react-jsx.d.ts": {"commit": "a9c59f8166b4d7f1e8c4309a506987c2e6d78b5e"} 

OSX Yosemite 10.10.4 

Вот мой демонстрационный компонент (смонтировать его и ввести букву в поисковой коробке, чтобы получить «неопределенные» внутри предупреждения) [уведомление, что вы должны прокручивать следующие блок кода ниже, чтобы увидеть весь код]

/// <reference path="../typings/react/react.d.ts" /> 

interface FilterListTestPropsInterface 
{} 

interface FilterListTestStateInterface 
{ 
    completeListItems : string[]; 
    displayedListItems : string[]; 
} 

class FilterListTestState implements FilterListTestStateInterface 
{ 
    completeListItems : string[]; 
    displayedListItems : string[]; 
    constructor(allItems: string[], displayedItems: string[]) 
    { 
    this.completeListItems = allItems, 
    this.displayedListItems = displayedItems 
    } 
} 

class FilterListTest extends React.Component<FilterListTestPropsInterface, FilterListTestStateInterface> 
{ 
    constructor(props:FilterListTestPropsInterface) 
    { 
    super(props); 
    } 

    // hardcoded values for testing/exploration purpose 
    initialState : FilterListTestStateInterface = 
    { 
    completeListItems : ["Apples", "Broccoli", "Chicken", "Duck", "Eggs", "Fish", "Granola", "Bash Brownies"], 
    displayedListItems : [] 
    } 

    componentWillMount() 
    { 
    this.setState(new FilterListTestState(this.initialState.completeListItems, this.initialState.completeListItems)); 
    } 

    filterList(event : React.SyntheticEvent) //used event:any then event.constructor.name to find the type 
    { 
alert(this.state + ' ' + this.state.displayedListItems); // debug result is object + undefined 
    var input : HTMLInputElement = event.target as HTMLInputElement; 
    var updatedList = this.state.completeListItems.filter 
    (
     function(item) 
     { 
     return item.toLowerCase().search(input.value.toLowerCase()) !== -1; 
     } 
    ); 
    this.setState 
    (
     { 
     completeListItems : this.initialState.completeListItems, 
     displayedListItems : updatedList 
     } 
    ); 
    } 

// here, state this.state.displayedListItems has the right values 
    render() 
    { 
    return (
     <div className="filter-list"> 
     <input type="text" placeholder="Search" onChange={this.filterList}/> 
     <FilterableList items={this.state.displayedListItems}/> 
     </div> 
    ); 
    } 
} 

class FilterableList extends React.Component<any, any> 
{ 
    constructor(props:any) 
    { 
    super(props); 
    } 

    render() 
    { 
    return (
     <ul> 
     { 
     this.props.items.map 
     (
      function(item) 
      { 
      return <li key={item}>{item}</li> 
      } 
     ) 
     } 
     </ul> 
    ); 
    } 
}; 

// mount this into a html doc with something like 
// React.render(<FilterListTest/>, document.getElementById('ReactContent')); 

Благодаря

ответ

1

Общая ошибка. Именно из-за пути this работы в JavaScript

Fix

Изменение filterList(event : React.SyntheticEvent) { к filterList = (event : React.SyntheticEvent) => {

Больше: https://www.youtube.com/watch?v=tvocUcbCupA и http://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

+0

Высокий, спасибо. (p.s. если это так распространено, было бы хорошо, если компилятор мог дать предупреждение) – Dom

+0

'this' в JavaScript ¯ \\ _ (ツ) _/¯. – basarat