首页 > 解决方案 > 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}
      />

标签: javascriptreactjsreact-nativeecmascript-6react-redux

解决方案


您可以设置一些字符条件或使用去抖动。

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)/>
  }}

推荐阅读