【发布时间】:2019-02-19 21:07:11
【问题描述】:
我正在构建我的第一个 react 原生应用并将我的应用连接到一个可模拟的 API
之前我有一个 data.js 文件,但最近想使用实时 API 测试应用程序。
现在我在通过 API 过滤时遇到问题。在此之前,我会导入我的 Data.JS 文件并提取对象并将其置于我的状态。然后我将它设置为等于过滤的对象。
现在我已经用我的 API 替换了我的数据文件
我有一个正在运行的测试here
我的期望:
通过我的 FlatList 过滤
我得到了什么:
undefined is not an object (evaluating 'row.restraunt.indexOf')
抓取 API
export default class FetchExample extends React.Component {
static navigationOptions = {
header: null,
};
constructor(props){
super(props);
this.state ={
isLoading: true,
}
}
componentDidMount(){
return fetch('https://demo3381137.mockable.io/')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.restraunts,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
通过 API 过滤
setSearchText(event) {
const searchText = event.nativeEvent.text;
// const textLength = this.state.rows.length;
const filteredTexts = this.state.dataSource.filter(row => {
return row.restraunt.indexOf(searchText) !== -1;
});
console.log("text: " + JSON.stringify(filteredTexts));
this.setState({
searchText,
filteredRows: filteredTexts
});
}
列表组件
renderRow = (rowData) => {
return (
<View>
<Text>
{rowData.item.restraunt}, {rowData.item.type}
</Text>
</View>
)
}
渲染平面列表
render() {
if(this.state.isLoading){
return(
<View style={styles.loading}>
<ActivityIndicator/>
</View>
)
}
return (
<View style={styles.container}>
{console.log(this.state.dataSource)}
<View style={styles.SearchBarContainer}>
<TextInput
placeholder="Search"
value={this.state.searchText}
onChange={this.setSearchText.bind(this)}
style={styles.searchBar}
underlineColorAndroid="black"
selectionColor="black"
/>
</View>
<FlatList
style={styles.listContainer}
data={this.state.dataSource}
renderItem={this.renderRow}
keyExtractor={(item, index) => index.toString()}
/>
</View>
)
}
【问题讨论】:
标签: reactjs react-native