【问题标题】:TypeError: Cannot read property 'contains' of nullTypeError:无法读取属性“包含”为空
【发布时间】:2020-05-03 17:03:53
【问题描述】:

我正在关注this algolia tutorial,我是 Gatsby 的新手。下面的代码目前似乎引起了问题。

我已从 search/index.js 文件中添加了其余代码...

import React, { useState, useEffect, createRef } from "react"
import { InstantSearch, Index, Hits, connectStateResults } from "react-instantsearch-dom"
import algoliasearch from "algoliasearch/lite"

import { Root, HitsWrapper, PoweredBy } from "./styles"
import Input from "./input"
import * as hitComps from "./hitComps"

const Results = connectStateResults(
    ({ searchState: state, searchResults: res, children }) =>
        res && res.nbHits > 0 ? children : `No results for '${state.query}'`
)

const Stats = connectStateResults(
    ({ searchResults: res }) =>
        res && res.nbHits > 0 && `${res.nbHits} result${res.nbHits > 1 ? `s` : ``}`
)

const useClickOutside = (ref, handler, events) => {
    if (!events) events = [`mousedown`, `touchstart`]
    const detectClickOutside = event =>
        !ref.current.contains(event.target) && handler()
    useEffect(() => {
        for (const event of events)
            document.addEventListener(event, detectClickOutside)
        return () => {
            for (const event of events)
                document.removeEventListener(event, detectClickOutside)
        }
    })
}

export default function Search({ indices, collapse, hitsAsGrid }) {
    const ref = createRef()
    const [query, setQuery] = useState(``)
    const [focus, setFocus] = useState(false)
    const searchClient = algoliasearch(
        process.env.GATSBY_ALGOLIA_APP_ID,
        process.env.GATSBY_ALGOLIA_SEARCH_KEY
    )
    useClickOutside(ref, () => setFocus(false))
    return (
        <InstantSearch
            searchClient={searchClient}
            indexName={indices[0].name}
            onSearchStateChange={({ query }) => setQuery(query)}
            root={{ Root, props: { ref } }}
        >
            <Input onFocus={() => setFocus(true)} {...{ collapse, focus }} />
            <HitsWrapper show={query.length > 0 && focus} asGrid={hitsAsGrid}>
                {indices.map(({ name, title, hitComp }) => (
                    <Index key={name} indexName={name}>
                        <header>
                            <h3>{title}</h3>
                            <Stats />
                        </header>
                        <Results>
                            <Hits hitComponent={hitComps[hitComp](() => setFocus(false))} />
                        </Results>
                    </Index>
                ))}
                <PoweredBy />
            </HitsWrapper>
        </InstantSearch>
    )
}

页面加载,然后点击屏幕上的任意位置会出现以下错误...

 TypeError: Cannot read property 'contains' of null
 HTMLDocument.detectClickOutside
 src/components/search/index.js:21
  18 | 
  19 | const useClickOutside = (ref, handler, events) => {
  20 |     if (!events) events = [`mousedown`, `touchstart`]
  21 |     const detectClickOutside = event =>
  22 |         !ref.current.contains(event.target) && handler()
  23 |     useEffect(() => {
  24 |         for (const event of events)

我确定这是一个非常基本的错误。如果有人有任何提示,我将不胜感激。谢谢。

【问题讨论】:

  • 请分享使用此钩子的组件,可能是您在组件中定义引用时出现的问题。
  • 谢谢。我已从该文件 (search/index.js) 中添加了其余代码
  • 最新版本的 React InstantSearch 上不存在 root 属性。您使用常规元素将侦听器挂钩。 github.com/algolia/react-instantsearch/blob/master/…
  • @samuel-vaillant 您的建议是正确的,这会导致其他已更新插件出现更多问题。非常感谢,我会继续努力的。

标签: reactjs gatsby algolia


【解决方案1】:

问题可能来自您定义参考时请使用 Facebook 建议的最佳实践。

我想你可能会做这样的事情:

const ref = React.createRef()

<InstanceSearch 
/* Your rest of your props */
ref={ref}
/>

【讨论】:

  • 谢谢。我试过了,当我点击某个地方时,我得到了一个不同的错误:“TypeError:ref.current.contains is not a function”。我不知道current来自哪里,也不知道它是什么。
  • 我可以给你一个代码示例吗,如果你愿意,你可以使用 CodeSandBox。 .current 来自 React
【解决方案2】:

我遇到了同样的问题,我通过在 search/index.js 中将 ref={ref} 添加到 &lt;HitsWrapper&gt; 来修复它。

<HitsWrapper ref = {ref} show={query.length > 0 && focus} asGrid={hitsAsGrid}>

【讨论】:

    猜你喜欢
    • 2021-09-26
    • 2021-03-02
    • 2021-12-21
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 2022-01-12
    • 2021-06-24
    • 1970-01-01
    相关资源
    最近更新 更多