【发布时间】:2022-01-12 13:17:48
【问题描述】:
我只在我的项目中使用功能组件,尽管如此,我还是收到了这个错误:Uncaught TypeError: Cannot call a class as a function。
这是我收到错误的父组件的一部分: (问题出在“withCheckCountry”组件上)
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/reset-password/:token" component={RestPass} />
<Route path="/programs" component={About} />
<Route path="/login" component={Login}>
{loggedIn() && <Redirect to={redirectionPath()} />}
</Route>
<Route path="/signUp" component={SignUp}>
{loggedIn() && <Redirect to={redirectionPath()} />}
</Route>
<Route
path="/country/:countryCode"
component={withCheckCountry(CountryApp, availableCountry, loadingCountry)}
/>
<Redirect to="/" />
</Switch>
这里是“withCheckCountry”组件:
import React, {useState, useEffect, memo} from 'react';
import PropTypes from 'prop-types';
import { Redirect } from 'react-router-dom';
import { toast } from 'react-toastify';
import ToastBody from "components/toastBody/toast";
import { FormattedMessage, injectIntl } from "react-intl";
const withCheckCountry = (Component, availableCountry, loadingCountry) => ({
...props
}) => {
//console.log("props = "+JSON.stringify(props));
if (!loadingCountry) {
const { countryCode } = props.match.params;
const isCountryExist = availableCountry.some(
country => country.countryCode === countryCode.toLocaleUpperCase(),
);
const [errorTitle, setErrorTitle] = useState(intl.formatMessage(messages.errorTitle));
const [countryNotExist, setCountryNotExist] = useState(intl.formatMessage(messages.countryNotExist));
useEffect(() => {
setErrorTitle(intl.formatMessage(messages.errorTitle));
setCountryNotExist(intl.formatMessage(messages.countryNotExist));
}, [intl]);
if (!isCountryExist) {
toast(() => <ToastBody title={errorTitle} message={countryNotExist} />);
return <Redirect to="/" />;
}
}
return <Component {...props} />;
};
withCheckCountry.propTypes = {
availableCountry: PropTypes.object,
};
export default injectIntl(withCheckCountry);
这个错误直到我在导出组件时添加了“injectIntl”后才出现,我需要它来从 props 中获取 intl,如果您有兴趣,可以在 documentation here 中看到。
【问题讨论】:
-
warpp 这个 injectIntl 围绕 Country App 而不是你的包装器。它期望得到组件而不是包装器。
-
但是文档说你只能在基于类的 React 组件中使用
injectIntl。您应该改用useIntl钩子。 -
injectIntl期望接收功能组件而不是 HOC -
@ZsoltMeszaros 感谢您的回复,我就是这样做的,我不得不将 react-intl 的版本升级到最新版本,并根据它更改了所有内容。
标签: javascript reactjs react-hooks intl