javascript - react-native 如何在输入时立即更新状态
问题描述
我正在尝试从用户那里获取输入并且它可以工作,但是在每个输入状态上都是更新并重新渲染组件。我想在用户键入一些查询时立即更新状态。现在例如,如果我输入 4 个字符,例如 (enta),那么我的组件会重新渲染 4 种类型。我想实现我的目标,例如用户类型(enta)然后我不会一次又一次地重新渲染。我只想重新渲染一次。有人可以帮我吗。
代码
<TextInput
style={styles.inputStyle}
placeholder="Search medicine and health products"
autoCapitalize="none"
onChangeText={(input)=>{
this.setState({
subCategoriesShow: true,
loader: true,
inputValue: value,
queries: [],
});
setTimeout(() => {
console.log("2@@@@@@@@@ ", this.state.inputValue);
axios
.get(
`${config.apiPath}/public/api/search`,
{
params: {
query: this.state.inputValue,
},
}
)
.then((res) => {
this.setState({
queries: res.data,
loader: false,
});
});
}, 3000);
}}
onBlur={handleBlur}
autoCorrect={false}
/>
解决方案
您可以设置一些字符条件或使用去抖动。
import * as _ from 'lodash';
componentDidMount = () => {
this.onChangeTextDelayed = _.debounce(this.onChangeData, 500);
}
onChangeData = (event) => {
//call some axios api and set the state.
}
<TextField
onChangeText={(event) => {
this.state.searchText = event
this.onChangeTextDelayed(event)/>
}}
推荐阅读
- javascript - 读取海关标头 HTTP
- c++11 - 为什么我尝试测试类中的成员变量(字符串)是否为空时会出现错误?
- python - 使用 str.replace 在循环中运行 XOR 加密不会更改某些字符
- javascript - 将对象从一个窗口传递到另一个窗口
- c++ - GCC_VERSION gcc-6.2.0 出现错误:enable_if 不是类模板,但相同的代码正在使用 gcc-4.3.0
- javascript - 如果我在一个数组中添加 2 个数字并推送到一个新数组,我如何从第二个数组中的值中找到这 2 个数字
- opencart - 如果 en-gb.php 语言文件仅在管理员中不起作用,如何修复
- python - 使用 Geoalchemy2 在 PostGis 中存储 WKBElement 会导致经度不正确
- python - 如何创建一个包含对手牌的黑白棋功能?
- javascript - 正则表达式使用 bootstrap-validate.js 将输入值设置在 1 到 10 之间