onChange useState后面一个字符

问题描述

我有一个简单的搜索组件,我想构建一个自动完成过滤器,但是我的onChange事件处理程序落后一个字符。

如果我在搜索栏中输入“ tsla”,则我的值为“ tsl”

<TextField
                className={classes.queryField}
                fullWidth
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <SvgIcon fontSize="small" color="action">
                        <SearchIcon />
                      </SvgIcon>
                    </InputAdornment>
                  )
                }}
                onChange={event => {
                  setValue(event.target.value);
                  setAuto(
                    tickers
                      .filter(
                        f =>
                          JSON.stringify(f)
                            .toLowerCase()
                            .indexOf(value) !== -1
                      )
                      .slice(0,10)
                  );
                  console.log(auto);
                }}
                value={value}
                placeholder="Search for a stock"
                variant="outlined"
              />

解决方法

问题是调用setAuto时您会使用旧的value变量。

const Search = (props) => {
  handleChange = (event) => {
    const value = event.target.value
    setValue(value);
    setAuto(tickers.filter((ticker) => JSON.stringify(ticker).toLowerCase().indexOf(value) !== -1).slice(0,10));
    console.log(auto);
  };

  return (
    <TextField
      className={classes.queryField}
      fullWidth
      InputProps={{
        startAdornment: (
          <InputAdornment position="start">
            <SvgIcon fontSize="small" color="action">
              <SearchIcon />
            </SvgIcon>
          </InputAdornment>
        ),}}
      onChange={handleChange}
      placeholder="Search for a stock"
      value={value}
      variant="outlined"
    />
  );
};

解决方案是将新值对象传递给setValue和setAuto。

  handleChange = (event) => {
    const value = event.target.value
    setValue(value);
    setAuto(tickers.filter((ticker) => JSON.stringify(ticker).toLowerCase().indexOf(value) !== -1).slice(0,10));
    console.log(auto);
  };