【问题标题】:React Search filter (hooks) through a High Order Component not working通过高阶组件的反应搜索过滤器(钩子)不起作用
【发布时间】:2021-01-27 13:01:02
【问题描述】:

我尝试让我的 React 搜索框过滤器工作。

请参阅 this sandbox 我目前所拥有的。

我有一个 HOC withSection.js,我在其中添加(现在)一个 <section> 标记到我的组件中:

const withSection = Component => props => (
  <section>
    <Component {...props} />
  </section>
)

然后在父组件中,我将我的 SearchBox 组件包装到这个 HOC 中并渲染它:

const SectionSearchBox = withSection(SearchBox);

<SectionSearchBox search={search} setSearch={setSearch} />

不知何故,一旦我将我的 SearchBox 包装到这个 HOC 中,它就会破坏功能?

这里有什么问题?

【问题讨论】:

  • 您确定有问题吗?我刚刚尝试了沙箱,在输入中输入了一个,它过滤了结果。我觉得不错。
  • @Gh05d 我更新了这个问题。我认为这与我的高阶组件有关......

标签: reactjs axios react-hooks use-effect use-state


【解决方案1】:

您需要在其父组件范围之外声明SectionSearchBox。在代码框示例中,它看起来像:

import withSection from "./hoc/withSection";
import SearchBox from "./SearchBox";

const SectionSearchBox = withSection(SearchBox);

function ArticlePage() {
  ...
};

否则,该组件的每个实例都将在其父组件的每个新渲染中重新创建(即,当搜索词更改时)。这导致搜索框在每次击键时都显得没有焦点,因为一个新的输入元素被放置在它的位置,其中包含上一次渲染的值。

【讨论】:

  • 比很多。所以因为useEffect。这是有道理的。
猜你喜欢
  • 2021-08-18
  • 1970-01-01
  • 2015-03-12
  • 2022-12-02
  • 1970-01-01
  • 2018-08-23
  • 2018-11-28
  • 2016-08-04
  • 2013-09-24
相关资源
最近更新 更多