【发布时间】:2017-07-12 14:41:58
【问题描述】:
我正在尝试使用 React 开发人员的 this example 来为表格创建搜索过滤器。
我的表格可以静态处理来自后端的数据。我为“样本”数据取出了一个数组,以使搜索功能正常工作。但是我很难理解他们如何使用“假数据”将他们的表填充为seen here,而不是像我想要的那样“只是”用测试数组填充它。
这是我的源代码。我想过滤“firstName”列,就像在 Facebook 的示例中一样(为简单起见)。错误源于调用 getSize() 时......但我怀疑问题出在其他地方。
class DataListWrapper {
constructor(indexMap, data) {
this._indexMap = indexMap;
this._data = data;
}
getSize() {
return this._indexMap.length;
}
getObjectAt(index) {
return this._data.getObjectAt(
this._indexMap[index],
);
}
}
class NameTable extends React.Component {
constructor(props) {
super(props);
this.testDataArr = []; // An array.
this._dataList = this.testDataArr;
console.log(JSON.stringify(this._dataList)); // It prints the array correctly.
this.state = {
filteredDataList: new DataListWrapper([], this._dataList)
};
this._onFilterChange = this._onFilterChange.bind(this);
}
_onFilterChange(e) {
if (!e.target.value) {
this.setState({
filteredDataList: this._dataList,
});
}
var filterBy = e.target.value;
var size = this._dataList.getSize();
var filteredIndexes = [];
for (var index = 0; index < size; index++) {
var {firstName} = this._dataList.getObjectAt(index);
if (firstName.indexOf(filterBy) !== -1) {
filteredIndexes.push(index);
}
}
this.setState({
filteredDataList: new DataListWrapper(filteredIndexes, this._dataList),
});
}
render() {
var filteredDataList = this.state.filteredDataList;
if (!filteredDataList) {
return <div>Loading table.. </div>;
}
var rowsCount = filteredDataList.getSize();
return (
<div>
<input onChange={this._onFilterChange} type="text" placeholder='Search for first name.. ' />
{/*A table goes here, which renders fine normally without the search filter. */}
</div>
);
}
}
export default NameTable
【问题讨论】:
-
很抱歉告诉你,但你做错了。首先,当您可以将对象存储在您的类中时,将其存储在状态中是非常糟糕的。您应该以您的状态存储:dataListLoaded。加载数据列表时,您必须设置 setState (dataListLoaded: true) 来重新渲染组件。
-
公平地说,我对 React 和一般前端的东西比较陌生。如果您可以提供您提到的内容的代码示例,我很乐意对其进行测试。
-
为了找到在 es6 中编码和反应的好方法,我看看这个:github.com/ryanmcdermott/clean-code-javascript 和一些像 material-ui 这样好的库的源代码
-
@cbll 你测试我的答案了吗?效果好吗?
标签: javascript facebook reactjs fixed-data-table