我試圖使用React開發人員使用this example爲表進行搜索過濾。React固定數據表:未捕獲TypeError:this._dataList.getSize不是函數
我有這張表可以很好地處理我後端數據的靜態數據。我已經拿出了一個「樣本」數據的數組來獲得搜索功能。但是我正在困難的時間圍繞他們如何使用「假數據」來填充他們的表格,如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。當你的datalist被加載時,你必須建立一個setState(dataListLoaded:true)來重組你的組件。 – Kornflexx
夠公平的,我對React和前端的東西比較陌生。如果你能提供你提到的東西的代碼示例,我很樂意去測試它。 – cbll
要找到在es6和反應中編碼的好方法,我看看這個:https://github.com/ryanmcdermott/clean-code-javascript和一些好的庫的源代碼,比如材料-ii – Kornflexx