How do I use react-i18next with a connected component

mde*_*eus 15 reactjs react-redux react-i18next

I would like to use react-i18next with my react-redux connected component and am not sure how to go about it.

I've simplified my code to show an example of a connected component:

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);
Run Code Online (Sandbox Code Playgroud)

Installed package versions:

react version: 16.8.4 
react-redux version: 5.1.1 
react-i18next version: 10.6.0
Run Code Online (Sandbox Code Playgroud)

What I've tried:

1) I get the error below when I use withTranslation, WithTranslation as follows:

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

Error:

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)
Run Code Online (Sandbox Code Playgroud)

2) I get the error below when I use withTranslation, WithTranslation as follows:

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

Error:

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)
Run Code Online (Sandbox Code Playgroud)

3) I cannot use useTranslation since hooks are not allowed to be used within a class.

I also tried the following:

... 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);
Run Code Online (Sandbox Code Playgroud)

but I get the following error:

Hooks can only be called inside the body of a function component. 
Run Code Online (Sandbox Code Playgroud)

Thank you in advance...

小智 5

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

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

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


kon*_*nqi 0

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

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

type InjectedProps = StateProps & ExternalProps & MyComponentsTranslations
export class MyComponent extends React.Component<InjectedProps> {
    ...
} 
Run Code Online (Sandbox Code Playgroud)

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

你可以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} />
  )
)
Run Code Online (Sandbox Code Playgroud)

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

您始终可以简单地将ti18n 的 -function 注入到您的组件中,但在我当前的项目中,我们认为它更干净

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

让我知道这是否适合您。

另外,为了使整个事情变得更加优雅,您可以使用这些助手:

export interface Translations<T> {
  translations: T
}

export const createTranslations = <T>(translations: T): Translations<T> => ({
  translations,
})
Run Code Online (Sandbox Code Playgroud)

这允许您设置

type InjectedProps = StateProps & Translations<MyComponentTranslations>
Run Code Online (Sandbox Code Playgroud)

并临时withNamespace

<MyConnectedComponent {...createTranslations<MyComponentTranslations>({ put translations here })} {...rest} />
Run Code Online (Sandbox Code Playgroud)