21

我想将 react-i18next 与我的 react-redux 连接组件一起使用,但不知道该怎么做。

我已经简化了我的代码来展示一个连接组件的例子:

import React from 'react';
import {connect} from 'react-redux';
import {userSelectors} from "./userSelectors";

interface IConnectedProps {
    activeUserName: string | undefined;
}
export class LandingPageComponent extends React.Component<IConnectedProps> {
    public render(): JSX.Element {
        return (
            <React.Suspense fallback={<Spinner/>}>
                <React.Fragment>
                    <div>
                    ... a bunch of controls using translated text
                    </div>
                    <div>{activeUserName}</div>
                </React.Fragment>
            </React.Suspense>
        );
    }
}

const mapStateToProps = (state: ICoreRootState) : IConnectedProps => ({
    activeUserName: userSelectors.getDisplayName(state),
});

export const LandingPage = connect(mapStateToProps)(LandingPageComponent);

已安装的软件包版本:

react version: 16.8.4 
react-redux version: 5.1.1 
react-i18next version: 10.6.0

我试过的:

1)当我使用withTranslation,WithTranslation时出现如下错误:

export class LandingPageComponent extends React.Component<IConnectedProps & WithTranslation> {...}
export const LandingPage = connect(mapStateToProps)(withTranslation()(LandingPageComponent));

错误:

The above error occurred in the <withI18nextTranslation(LandingPageComponent)> component:
    in withI18nextTranslation(LandingPageComponent) (created by Connect(withI18nextTranslation(LandingPageComponent)))
    in Connect(withI18nextTranslation(LandingPageComponent))
    in Route
    in t
    in Connect(t) (at App.tsx:49)
    in Switch (at App.tsx:45)
    in App (at src/index.tsx:14)
    in Router (created by ConnectedRouter)
    in ConnectedRouter (created by Connect(ConnectedRouter))
    in Connect(ConnectedRouter) (at src/index.tsx:13)
    in Provider (at src/index.tsx:12)

2)当我使用withTranslation,WithTranslation时出现以下错误,如下所示:

export class LandingPageComponent extends React.Component<IConnectedProps & WithTranslation> {...}
export const LandingPage = withTranslation()(connect(mapStateToProps)(LandingPageComponent));

错误:

index.js:1446 The above error occurred in the <withI18nextTranslation(Connect(LandingPageComponent))> component:
    in withI18nextTranslation(Connect(LandingPageComponent))
    in Route
    in t
    in Connect(t) (at App.tsx:49)
    in Switch (at App.tsx:45)
    in App (at src/index.tsx:14)
    in Router (created by ConnectedRouter)
    in ConnectedRouter (created by Connect(ConnectedRouter))
    in Connect(ConnectedRouter) (at src/index.tsx:13)
    in Provider (at src/index.tsx:12)

3) 我不能使用 useTranslation 因为钩子不允许在类中使用。

我还尝试了以下方法:

... a bunch of imports
interface ILogoutButtonProps {
    userName?: string;
}
interface IConnectedHandlers {
    readonly logout: any;
    readonly push: any;
}
class InnerLogoutComponent extends React.Component<IButtonProps & IConnectedHandlers & ILogoutButtonProps & WithTranslation, {}> {

    public render() {
        const {userName, onClick, logout: Logout, push: Push, ...buttonProps} = this.props;
        const logoutText = this.props.i18n.t(StringNames.logout);
        const buttonText = userName ? logoutText + " " + userName : logoutText;
        return (
            <Button {...buttonProps} text={buttonText} onClick={this.handleClick}/>
        );
    }

    private handleClick = (event: React.MouseEvent<HTMLElement>) : void => {
        this.props.logout()
            .then(() => this.props.push(LoginPaths.verifyUser));
    }
}
const InnerLogoutTranslatedComponent = withTranslation()(InnerLogoutComponent);

class LogoutComponentInternal extends React.Component<IButtonProps & IConnectedHandlers & ILogoutButtonProps, {}> {
    public render () {
        return (
            <InnerLogoutTranslatedComponent {...this.props}/>
        );
    }
}
export const LogoutComponent = connect(null,{logout, push})(LogoutComponentInternal);

但我收到以下错误:

Hooks can only be called inside the body of a function component. 

先感谢您...

4

5 回答 5

5

在我们的项目中,我们成功地利用了这个:

import { compose } from 'redux';
import { withNamespaces } from 'react-i18next';
import { connect } from 'react-redux';
...
export default compose(withNamespaces('translation'), connect(mapStateToProps))(ComponentName);

有了这个,我们用mapStateToProps连接到Redux并且我们有了翻译

于 2019-08-18T11:50:00.213 回答
4

我将 SSR 与 RazzleJS 一起使用,在我的情况下它工作得非常好。我像这样连接我connectwithTranslation

export default connect(mapStateToProps,mapDispatchToProps)(withTranslation()(Component));
于 2019-10-31T15:00:16.933 回答
1

这对我有用:

export default withTranslation()(connect(mapStateToProps, mapDispatchToProps)(Component));
于 2020-01-28T00:06:51.840 回答
0

就我而言,我通过以下方式修复了它:

export default withTranslation(null, {withRef: true})(MyComponent);

withReffalse默认情况下。

来源:https ://github.com/i18next/react-i18next/blob/master/src/withTranslation.js

于 2019-06-12T09:03:23.850 回答
0

实际上,我很难确定将组件包装在 HOC 中的顺序。在我目前工作的项目中,我们像 wrap 一样withNamespaces(connect(withStyles(component))),效果很好(withNamespaces本质上与 相同withTranslations)。我们在尝试连接翻译的组件时遇到了问题,您现在可能遇到了同样的问题。所以这是我们的做法:

您有一个“正常”组件,例如

type InjectedProps = StateProps & ExternalProps & MyComponentsTranslations
export class MyComponent extends React.Component<InjectedProps> {
    ...
} 

(注意:该过程与功能组件完全相同)

你可以const MyConnectedComponent = connect(mapStateToProps, mapDispatchToProps)(MyComponent)

最后,你做一个

import {WithNamespaces, withNamespaces} from "react-i18next"
export const LocalizedMyComponent = withNamespaces()(
  ({t,...rest}): WithNamepsaces) => (
    <MyConnectedComponent translations={{ put translations here }} {...rest} />
  )
)

现在,诀窍是我们定义了一个interface MyComponentsTranslations {}放置所有必需翻译或翻译函数的位置(如果是复数)。 MyComponentsTranslations被添加到InjectedProps以使它们在原始组件中可用。

您总是可以简单地将ti18n 的 -function 注入到您的组件中,但在我当前的项目中,我们认为它更清洁

  • 显式命名组件所需的翻译
  • 由于原始组件和连接组件都不依赖于 t 函数,因此它们很容易测试

让我知道这是否适合您。

此外,为了让整个事情更优雅一点,你可以使用这些助手:

export interface Translations<T> {
  translations: T
}

export const createTranslations = <T>(translations: T): Translations<T> => ({
  translations,
})

这允许您设置

type InjectedProps = StateProps & Translations<MyComponentTranslations>

withNamespacehoc 中:

<MyConnectedComponent {...createTranslations<MyComponentTranslations>({ put translations here })} {...rest} />
于 2019-05-27T15:20:05.273 回答