简体   繁体   English

如何在输入反应本机时立即更新 state

[英]How to update state at once on input in react native

I am trying to take input from user and it working but on every input state is update and re render the component.我正在尝试从用户那里获取输入并且它可以正常工作,但是在每个输入 state 上都会更新并重新渲染组件。 I want to update state at once when user type some query.当用户键入一些查询时,我想立即更新 state。 Now for example if I type 4 characters like ( enta ) then my component re-render 4 types.现在例如,如果我输入 4 个字符,例如 (enta),那么我的组件会重新渲染 4 种类型。 I want to achieve my goal if for example user type ( enta ) then I don't re-render again and again.如果例如用户类型( enta )然后我不会一次又一次地重新渲染,我想实现我的目标。 I just want to re-render one time.我只想重新渲染一次。 Could someone please help me.有人可以帮助我。

Code代码

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

You can set some character condition or used debounce.您可以设置一些字符条件或使用去抖动。

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

You could look into something along the lines of lodash.debounce您可以按照lodash.debounce的方式查看一些内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM