第16行:有条件地调用React Hook“ useState”

时间:2019-10-02 14:43:48

标签: reactjs

enter image description here

const Credits = ({ cast, baseUrl }) => {
  if (!cast) {
    return;
  }
  const [totalShow, setTotalShow] = useState(null);
  const sliderElement = useRef();

  // Set amount of items to show on slider based on the width of the element
  const changeTotalShow = () => {
    let totalItems = Math.round(sliderElement.current.offsetWidth / 70);
    if (totalItems > cast.length) {
      totalItems = cast.length;
    }
    setTotalShow(totalItems);
  };

  const items = cast.map(person => ());

  useEffect(() => {
    changeTotalShow();
    window.addEventListener("resize", changeTotalShow);
    return () => window.removeEventListener("resize", changeTotalShow);
  }, []);

  const settings = {
    dots: false,
    infinite: true,
    autoplay: true,
    autoplaySpeed: 3000,
    swipeToSlide: true,
    speed: 500,
    slidesToShow: totalShow,
    slidesToScroll: 1,
    nextArrow: ,
    prevArrow: ,
  };

  return { items };
};

1 个答案:

答案 0 :(得分:0)

首先,您应该看一下rule of hooks,以便了解使用钩子可以做什么和不能做什么。您会注意到,不能有条件地调用钩子,这意味着每个渲染器应具有相同数量的钩子。您不知道,如果!credits渲染器将不会调用任何东西。我想你是否会搬走

  if (!cast) {
    return;
  }

警告/错误将消失。