简体   繁体   English

React Hook useEffect 缺少依赖项:'context'。 包括它或删除依赖项数组

[英]React Hook useEffect has a missing dependency: 'context'. Either include it or remove the dependency array

My goal is to make an API request when user types something on input.我的目标是在用户输入内容时发出 API 请求。 I'm getting the data successfully.我正在成功获取数据。 However the component is rerendering twice and giving me this warning.但是该组件正在重新渲染两次并给我这个警告。 If I include 'context' I'm getting an infinite loop.如果我包括“上下文”,我会得到一个无限循环。 Here's my code:这是我的代码:

Component.js:组件.js:


const SearchBox = () => {
  const [searchTerm, setSearchTerm] = useState("");
  const { handleSearch, searchResults } = useContext(MovieContext);

  console.log(searchResults);

  useEffect(() => {
    let timer;
    timer = setTimeout(() => {
      handleSearch(searchTerm);
    }, 500);

    return () => clearTimeout(timer);
  }, [searchTerm]);

  const renderResults = () => {
    if (searchResults.length > 0) {
      searchResults.map(result => {
        return (
          <div key={result.Title}>
            <img src={result.Poster} alt={result.Title} />;
          </div>
        );
      });
    }
    return;
  };

  return (
    <>
      <label>
        <b>Search</b>
      </label>
      <input
        className="input"
        value={searchTerm}
        onChange={e => setSearchTerm(e.target.value)}
      />
      <div className="dropdown is-active">
        <div className="dropdown-menu">
          <div className="dropdown-content results">{renderResults()}</div>
        </div>
      </div>
    </>
  );
};

On top of this context.searchResults is undefined, although I set the initial value as an empty array.在这个 context.searchResults 之上是未定义的,尽管我将初始值设置为一个空数组。 I wanted to know what causing this.我想知道这是什么原因造成的。 What am I doing wrong?我究竟做错了什么? Here is my context code below:这是我的上下文代码如下:

Context.js:上下文.js:

const Context = React.createContext("");

export class MovieStore extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchResults: [],
      handleSearch: this.handleSearch
    };
  }

  handleSearch = async term => {
    try {
      if (term !== "") {
        const response = await axios.get("http://www.omdbapi.com/", {
          params: {
            apikey: apikey,
            s: term
          }
        });
        this.setState({ searchResults: response.data.Search });
      }
    } catch (error) {
      console.log(error);
    }
  };

  render() {
    return (
      <Context.Provider value={this.state}>
        {this.props.children}
      </Context.Provider>
    );
  }
}

Exactly the same thing about an infinite loop is mentioned in React docs here .这里的React文档中提到了关于无限循环的完全相同的事情。 So the cause of infinite loop is that, in context render function, you create new value every time render is called.所以无限循环的原因是,在上下文渲染函数中,每次调用渲染时都会创建值。

  render() {
    return (
      <Context.Provider
        // ! value object creates every time render is called - it's bad
        value={{ ...this.state, handleSearch: this.handleSearch }}
      >
        {this.props.children}
      </Context.Provider>
    );
  }

It causes every consumer to rerender when context state updates.当上下文状态更新时,它会导致每个消费者重新渲染。 So, if you put context in dependencies array of useEffect , eventually, it'll cause an infinite loop, because context value is always different.因此,如果您将context放在useEffect依赖项数组中,最终会导致无限循环,因为context值总是不同的。 Here's what happens:这是发生的事情:

  1. Context makes a search query.上下文进行搜索查询。

  2. Context state updates with the new data, which causes all consumers to rerender.使用新数据更新上下文状态,这会导致所有消费者重新渲染。

  3. In context consumer useEffect sees that context value has been updated and it calls setTimeout which will call for another search in context provider in 500ms.在上下文中,消费者useEffect看到上下文值已更新,并调用setTimeout ,这将在 500 毫秒内调用上下文提供程序中的另一次搜索。

  4. Consumer calls context to make another search query and we've got an infinite loop!消费者调用上下文进行另一个搜索查询,我们得到了一个无限循环!

The solution is to keep context value the same object, while only updating its properties.解决方案是保持上下文值相同的对象,同时只更新其属性。 It can be done by putting all the necessary properties inside of context state.它可以通过将所有必要的属性放在上下文状态中来完成。 Like that:像那样:

export class MovieStore extends Component {
  handleSearch = async term => {
    try {
      if (term !== "") {
        const response = await axios.get("http://www.omdbapi.com/", {
          params: {
            apikey: "15bfc1e3",
            s: term
          }
        });
        this.setState({ searchResults: response.data.Search });
      }
    } catch (error) {
      console.log(error);
    }
  };

  state = {
    searchResults: [],
    handleSearch: this.handleSearch // <~ put method directly to the state
  };

  render() {
    return (
      <Context.Provider value={this.state}> // <~ Just returning state here
        {this.props.children}
      </Context.Provider>
    );
  }
}

Hope it helps <3希望有帮助 <3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React Hook useEffect 缺少依赖项:&#39;formData&#39;。 包括它或删除依赖项数组。 什么是依赖就是使用 - React Hook useEffect has a missing dependency: 'formData'. Either include it or remove the dependency array. what is dependency is use React Hook useEffect 缺少一个依赖项:'handleLogout'。 要么包含它,要么移除依赖数组 react - React Hook useEffect has a missing dependency: 'handleLogout'. Either include it or remove the dependency array react React Hook React.useEffect 缺少依赖项:“loadData”。 包含它或删除依赖项数组 - React Hook React.useEffect has a missing dependency: 'loadData'. Either include it or remove the dependency array React Hook useEffect 缺少依赖项:&#39;props.myObj&#39;。 包括它或删除依赖项数组 - React Hook useEffect has a missing dependency: 'props.myObj'. Either include it or remove the dependency array React Hook useEffect 缺少依赖项:'evaluate'。 包括它或删除依赖数组 - React Hook useEffect has a missing dependency: 'evaluate'. Either include it or remove the dependency array 第 31:7 行:React Hook useEffect 缺少依赖项:'url'。 包括它还是删除依赖数组? - Line 31:7: React Hook useEffect has a missing dependency: 'url'. Either include it or remove the dependency array? React Hook useEffect 缺少一个依赖项:'reduxArray'。 包括它或删除依赖数组 - React Hook useEffect has a missing dependency: 'reduxArray'. Either include it or remove the dependency array React Hook useEffect 缺少依赖项:'data'。 包括它或删除依赖数组 - React Hook useEffect has a missing dependency: 'data'. Either include it or remove the dependency array React Hook useEffect 缺少依赖项:“match.params.roomid”。 包含它或删除依赖项数组 - React Hook useEffect has a missing dependency: 'match.params.roomid'. Either include it or remove the dependency array React Hook useEffect 缺少依赖项:&#39;fetchTracker&#39;。 包括它或删除依赖项数组 - React Hook useEffect has a missing dependency: 'fetchTracker'. Either include it or remove the dependency array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM