【问题标题】:Use Hook to populate state in React在 React 中使用 Hook 填充状态
【发布时间】:2021-04-16 01:39:41
【问题描述】:

我正在尝试使用 Hook 以以下方式填充状态。

class CreateService extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      serviceToUSe: []
    };
  }


  useEffect(() => {
    if (window.location.hostname == 'myhost') {
        this.setState({ serviceToUSe: require('../public/service/myhost.com.json') })
    } else {
      this.setState({ serviceToUSe: require('../public/service/default.json') })
    }
    });
  
}

我想在加载组件时填充serviceToUSe。但我遇到了错误。

【问题讨论】:

  • 钩子用于功能组件。你不能在类组件中使用它们

标签: reactjs react-hooks


【解决方案1】:

你不能在类组件中使用 Hooks。钩子只能在功能组件中使用

const CreateService = () => {

  const [serviceToUse, setServiceToUse] = useState([])
   


  useEffect(() => {
    if (window.location.hostname == 'myhost') {
      setServiceToUse([require('../public/service/myhost.com.json'])
    } else {
      setServiceToUse([require('../public/service/default.json')])
    }
  }, []);
  
}

你的钩子语法也不正确。详细了解Hooks

【讨论】:

  • 感谢@Pushkin 的回复。您的CreateService 会在加载组件时调用吗?
  • “加载组件时调用”,你的意思是同一个组件还是另一个组件。您打算将其用作 Angular 服务吗?
  • 谢谢@Pushkin。我的意思是相同的组件。我可以在 Class Component 中使用什么而不是 Hooks (useEffect) ?谢谢。
  • 它将在加载时运行。对于类方法,请查看生命周期方法。在这种情况下,您可以使用 componentDidMount()
  • @DrewReese,谢谢,我没注意到this
猜你喜欢
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-21
  • 2020-07-01
  • 1970-01-01
相关资源
最近更新 更多