收到错误“在渲染其他组件时无法更新组件”。实现我正在尝试的正确方法是什么?

时间:2020-08-11 19:35:08

标签: javascript reactjs react-hooks

如标题中所述,我目前遇到以下错误:呈现其他组件(HomePage)时无法更新组件(Query)。

我对React还是很陌生,尽管我想知道我正在打破规则(仅在顶层使用钩子来保留调用它们的顺序),但我不确定如何实现我正在尝试的另一种方式。

目标是如果后端没有任何采访,则设置setPreLaunch(true)。这段代码可以完成工作,但是会引发错误。我尝试将钩子作为道具发送到Interviews组件并在那里进行处理,但是遇到了相同的错误。

这是有问题的代码:

import React, { useState } from "react";
import Interviews from "../../components/Interviews";
import Query from "../../components/Query";
import INTERVIEWS_QUERY from "../../queries/interviews/interviews";
import {
  Row,
  Col,
  Button,
  InputGroup,
  FormControl,
  Form,
} from "react-bootstrap";
import Filters from "../../components/Filters";
import jsonp from "jsonp";
import queryString from "query-string";

const HomePage = () => {
  const [genre, setGenre] = useState(["Any"]);
  const [authorHistory, setAuthorHistory] = useState(["Any"]);
  const [preLaunch, setPreLaunch] = useState(false);
  const [emailEntered, setEmailEntered] = useState("");
  const [emailMessage, setEmailMessage] = useState("");

  if (!preLaunch) {
    return (
      <div>
        <Row id="home-banner-container">
          <Col md={12}>
            {" "}
            <h1 id="home-main-heading" className="text-center">
              Text
            </h1>
            <p id="home-sub-heading" className="text-center">
              Text
            </p>
          </Col>
        </Row>
        <Row>
          <Col md={3}>
            <Filters
              genre={genre}
              setGenre={setGenre}
              authorHistory={authorHistory}
              setAuthorHistory={setAuthorHistory}
            />
            <div className="contact-blurb">
              Text
            </div>
            <Button variant="primary" className="contact-blurb-btn">
              Contact
            </Button>{" "}
          </Col>
          <Col md={9}>
            <Query query={INTERVIEWS_QUERY}>
              {({ data: { interviews } }) => {
                if (interviews.length < 1) {
                  setPreLaunch(true);
                } else {
                  setPreLaunch(false);
                }
                return (
                  <Interviews
                    interviews={interviews}
                    genreFilter={genre}
                    authorHistoryFilter={authorHistory}
                  />
                );
              }}
            </Query>
          </Col>
        </Row>
      </div>
    );
  } else {
    return (
      <div>
        <Row id="home-banner-container">
          <Col md={12}>
            {" "}
            <h1 id="home-main-heading" className="text-center">
              Text
            </h1>
            <p id="home-sub-heading" className="text-center">
              Text
            </p>
          </Col>
        </Row>
        <Row>
          <Col md={{ span: 6, offset: 3 }}>
            <Form
              onSubmit={subscribeToNewsLetter}
              className="prelaunch-email-form"
            >
              <InputGroup className="mb-3">
                <FormControl
                  placeholder="Email Address"
                  aria-label="Email Address"
                  type="email"
                  onChange={(e) => setEmailEntered(e.target.value)}
                  value={emailEntered}
                  className="prelaunch-email-input"
                />
                <InputGroup.Append>
                  <Button
                    variant="outline-secondary"
                    type="Submit"
                    className="prelaunch-email-btn"
                  >
                    Keep Me Updated
                  </Button>
                </InputGroup.Append>
              </InputGroup>
              <p>{emailMessage}</p>
            </Form>
          </Col>
        </Row>
        <Row>
          <Col md={3}></Col>
          <Col md={9}>
            <Query query={INTERVIEWS_QUERY}>
              {({ data: { interviews } }) => {
                if (interviews.length < 1) {
                  setPreLaunch(true);
                } else {
                  setPreLaunch(false);
                }
                return (
                  <Interviews
                    interviews={interviews}
                    genreFilter={genre}
                    authorHistoryFilter={authorHistory}
                  />
                );
              }}
            </Query>
          </Col>
        </Row>
      </div>
    );
  }
};

export default HomePage;

编辑

这是更新的Homepage代码,其中包含Hero推荐的Query回调。

  const [genre, setGenre] = useState(["Any"]);
  const [authorHistory, setAuthorHistory] = useState(["Any"]);
  const [preLaunch, setPreLaunch] = useState(false);
  const [emailEntered, setEmailEntered] = useState("");
  const [emailMessage, setEmailMessage] = useState("");

  const onInterviewsReady = (interviews) => {
    setPreLaunch(interviews.length < 1);
  };

  const myQuery = (
    <Query
      query={INTERVIEWS_QUERY}
      onInterviewsReady={(i) => onInterviewsReady(i)}
    >
      {({ data: { interviews } }) => {
        return (
          <Interviews
            interviews={interviews}
            genreFilter={genre}
            authorHistoryFilter={authorHistory}
          />
        );
      }}
    </Query>
  );

  ...

这是完整的查询文件:

import React from "react";
import { useQuery } from "@apollo/react-hooks";

const Query = ({ children, query, id, onInterviewsReady }) => {
  const { data, loading, error } = useQuery(query, {
    variables: { id: id },
  });

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {JSON.stringify(error)}</p>;
  if (onInterviewsReady) {
    onInterviewsReady(data.interviews);
  }
  return children({ data });
};

export default Query;

使用此更新的代码,结果是相同的。一个正常运行的网站会引发与以前相同的错误。

1 个答案:

答案 0 :(得分:2)

如果访谈是在Query中异步获取的,那么一个简单的解决方法可能是:

  • onInterviewsReady组件引入新的回调道具Query
  • 在面试准备好后,让Query立即以效果(useEffect)调用此回调
    • 不使用效果仍然会导致渲染Query时异物的状态发生变化,从而产生警告
  • 由托管组件HomePage使用const onInterviewsReady = interviews => setPreLaunch(interviews.length < 1);之类的函数实现回调,并将其传递给Query
  • 如果您遇到不必要的重新渲染,则可以通过修改以下任一方法来确保回调引用稳定
    • 主机组件(HomePage):在将回调定义传递给使用组件之前,将回调定义包装在useCallback
    • 消耗组件(Query):将传递的回调道具包装在useRef中,并在效果中调用引用的当前值,而不是道具的值