将文本输入中的值存储到redux存储中会导致重新渲染react组件

时间:2020-09-11 19:57:47

标签: reactjs redux react-redux redux-toolkit

我正在尝试将文本输入中的值存储到redux存储中,但问题是我的react组件仍在重新呈现。

在使用反跳动作分派动作之后,组件自动完成重新呈现,我得到了初始状态。因此,由于反跳功能,输入在300ms后变为空。

我尝试使用 useCallback 避免它,但没有任何结果。

如何将输入值保存到redux存储中并防止重新渲染React组件?

const AutoComplete = () => {
  const [focus, setFocus] = useState(false);
  const [blur, setBlur] = useState(false);
  const radarTrends = useSelector(selectedRadarsTrends);
  const dispatch = useDispatch();
  const filteredValue = useSelector(selectedFilteredValue);


  const debounceFilteredValue = (value) => {
      dispatch(setFilteredValue(value));
   }

  const debounce = useCallback(_.debounce(debounceFilteredValue, 300), []);

  const handleOnChange = (event) => {
    debounce(event.target.value);
  };

  const handleOnFocus = () => {
    setBlur(false);
    setFocus(true);
  };

  const handleOnBlur = () => {
    setFocus(false);
    setBlur(true);
  };
  return (
    <StyledAutoComplete hasFocus={focus} hasBlur={blur}>
      <StyledMagnifier>
        <Magnifier width={20} height={20} />
      </StyledMagnifier>
      <Input
        placeholder="type trend name"
        type="text"
        label=""
        name="autocomplete"
        onFocus={handleOnFocus}
        onChange={handleOnChange}
        onBlur={handleOnBlur}
      />
    </StyledAutoComplete>
  );
};

感谢帮助。

1 个答案:

答案 0 :(得分:0)

我相信re-render是由useSelector之后的dispatch引起的。

When an action is dispatched, useSelector() will do a reference comparison of
the previous selector result value and the current result value.
If they are different, the component will be forced to re-render.
If they are the same, the component will not re-render.

查看文档:{​​{3}}