reactjs 尝试在react组件的useEffect中添加一些代码

flvlnr44  于 2023-02-15  发布在  React
关注(0)|答案(2)|浏览(140)

我正在学习react并尝试使用useEffect。但是我得到了这个错误:

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

为了解决第一个问题,我检查了react和react-dom版本,它们是相同的18.2.0。为了解决第二个问题,我不认为我是(代码即将发布)。我不知道如何检查第三个问题,我不认为有,但又不确定。下面是我的代码:

import React, { useEffect } from "react";

useEffect(() => {
  document.title = `Greetings to aaaa`;
}, []);

class CustomerOnboarding extends React.Component {
  render() {
    return (
      <div></div>
    );
  }
}

export default CustomerOnboarding;

上面的代码抛出了Invalid hook call错误,但是当我把useEffect放到component类中时,我得到了一个稍微不同的错误:

我不知道这是否有关系,但是我使用react with ruby on rails,我有其他的组件工作的很好,没有钩子,有什么想法吗?

wztqucjr

wztqucjr1#

useEffect用于功能组件。对于类组件,您需要使用componentDidUpdate和componentDidMount
在您的情况下:

import React  from "react";

class CustomerOnboarding extends React.Component {
  componentDidMount() { // this is for class component
    document.title = `Greetings to aaaa`;
  }
  render() {
    return (
      <div></div>
    );
  }
}

export default CustomerOnboarding;

要使用useEffect,您可以将组件更改为功能组件:

import React, { useEffect } from "react";

function CustomerOnboarding() {
  useEffect(()=>{
    document.title = `Greetings to aaaa`;
  },[]);
  return (
    <div></div>
  );
}

export default CustomerOnboarding;
643ylb08

643ylb082#

或者你可以把你的组件转换成如下的函数

import React, { useEffect } from "react";

const CustomerOnboarding = () => {
  useEffect(() => {
    document.title = `Greetings to aaaa`;
  }, []);

  return <div></div>;
};

export default CustomerOnboarding;

相关问题