ReferenceError: window is not defined, when trying to sync the search input state with react instant search

ReferenceError: window is not defined, when trying to sync the search input state with react instant search

我正在使用 next js,我正在尝试将我的搜索状态与 url 查询参数同步,以便在导航过程中我不会丢失我的搜索输入状态。

我知道这是一种服务器端语言,但我该怎么做才能使此代码与 window 对象一起工作?

这是来自官方 algolia 示例的代码片段 - https://github.com/algolia/react-instantsearch/blob/master/examples/media/URLSync.js

import React, { Component } from "react";
import qs from "qs";

const updateAfter = 700;
const searchStateToURL = (searchState) =>
  searchState ? `${window.location.pathname}?${qs.stringify(searchState)}` : "";

const withURLSync = (TestSearch) =>
  class WithURLSync extends Component {
    state = {
      searchState: qs.parse(window.location.search.slice(1)),
    };

    componentDidMount() {
      window.addEventListener("popstate", this.onPopState);
    }

    componentWillUnmount() {
      clearTimeout(this.debouncedSetState);
      window.removeEventListener("popstate", this.onPopState);
    }

    onPopState = ({ state }) =>
      this.setState({
        searchState: state || {},
      });

    onSearchStateChange = (searchState) => {
      clearTimeout(this.debouncedSetState);

      this.debouncedSetState = setTimeout(() => {
        window.history.pushState(
          searchState,
          null,
          searchStateToURL(searchState)
        );
      }, updateAfter);

      this.setState({ searchState });
    };

    render() {
      const { searchState } = this.state;

      return (
        <TestSearch
          {...this.props}
          searchState={searchState}
          onSearchStateChange={this.onSearchStateChange}
          createURL={searchStateToURL}
        />
      );
    }
  };

export default withURLSync;

它适用于 React js,但我如何才能使此代码片段适用于 next.js?

您应该将使用 window 的所有内容放在 if 语句下,检查代码是 运行 客户端还是服务器端。 例如创建一个这样的函数:

export const isClient = () => !(typeof window === "undefined");

或者只是一个变量:

export const isClient = !(typeof window === "undefined");

在您的情况下,您可以这样做(使用变量 one):

componentDidMount() {
  if(isClient) {
    window.addEventListener("popstate", this.onPopState);
  }
}

这样你就可以确保你的代码运行时 window 不是 undefined