android - 当我在搜索中输入内容时如何更新我的列表?
问题描述
search = () => {
fetch(strings.baseUri+"search_by_name", {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"name": this.state.name,
})
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({data: responseJson});
})
.catch((error) => {
console.error(error);
});
}
每当我在搜索框中输入内容时,如何使用搜索功能更新我的列表?
这就是我在 TextInput (SearchBox) 中尝试的。
<TextInput style={styles.searchInput}
placeholder="Search"
placeholderTextColor= {colors.whiteColor}
onChangeText={
name => {
this.setState({name});
this.search();
}
}
/>
解决方案
首先responseJson
是一个实际的 json 对象,您不需要对其进行字符串化然后解析它。
您可以将 responseJson 存储在状态中
search = () => {
fetch(strings.baseUri+"search_by_name", {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"name": this.state.name,
})
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({data: responseJson});
})
.catch((error) => {
console.error(error);
});
}
只需确保在组件的构造函数中设置初始状态
constructor(props) {
super(props);
this.state = { data: [] }
}
然后你应该能够通过使用访问你的数据this.state.data
更新问题的更新答案
问题是您没有意识到 setState 是异步的。那就是状态更新需要时间。这意味着您正在设置状态,然后希望在调用下一个函数时状态已经更新。不幸的是,在 TextInput 中调用 setState 并没有达到预期的效果。
我会将您的搜索功能更新为以下内容
search = (name) => {
fetch(strings.baseUri+"search_by_name", {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"name": name,
})
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({data: responseJson, name: name});
})
.catch((error) => {
this.setState({name: name});
console.error(error);
});
}
然后在你TextInput
更新你的函数调用
<TextInput style={styles.searchInput}
placeholder="Search"
placeholderTextColor={colors.whiteColor}
onChangeText={ name => {
if (name.length > 0) {
this.search(name);
} else {
this.setState({data: [], name: ''});
}
}
}
/>
这将减少调用 setState 的次数。
推荐阅读
- javascript - ~ 导入 scss 的符号正在 Angular 6 中的 node_modules 内搜索
- autohotkey - 在 Autohotkey 中检测 Alt+LeftMouse 单击并发送延迟双击
- postgresql - 使用动态目标列进行查询
- python - Python - 日期格式
- angular - 在组件模板中使用“this”调用变量或方法是一种好习惯吗?
- qt - 根据 listElement 键切换 listView 的委托
- pip - 无法导入gym;ModuleNotFoundError:没有名为“gym”的模块
- hadoop - 设计 MapReduce 函数以查找集合列表之间的交集
- php - 在 woocommerce 中使用 if else 评分
- javascript - 用于将迭代值(例如数组元素)插入 HTML 的简单 JavaScript 模板文字