我是整个生态系统的新手,我想知道为什么在我的示例组件中 render 函数this.state.displayedListItems
是一个字符串数组,正如预期的那样,但在 filterList中函数this.state.displayedListItems
未定义?
我正在使用
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
这是我的演示组件(安装它并在搜索框中键入一个字母以在警报中获取'undefined')[注意您必须滚动以下代码块以查看整个代码]
/// <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'));
由于
答案 0 :(得分:1)
常见错误。这是因为this
在JavaScript中的工作方式
将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