FormattedMessage (реагировать-Intl) возвращает [объект объекта] даже после обертывания компонента с injectIntl ​​(React-Intl) и получения ошибки - PullRequest
0 голосов
/ 15 декабря 2018

FormattedMessage возвращает компонент (обернутый тегом span), и мы не можем использовать его в параметре-заполнителе, поэтому я настроил конфигурацию IntlProvider для возврата отформатированного сообщения без тега span.Вначале приведена конфигурация IntlProvider:

import React from 'react';
import {
  FormattedMessage,
  IntlProvider,
} from 'react-intl';

import enUSMessages from 'core/l10n/messages/en-US.json';

// This module does two things:
// 1. It provides an abstraction for how localization is done, decoupling the app from the
//    specific implementation, e.g. if we swapped out react-intl for something else, we'd just
//    need to change this file.
// 2. It enforces types, i.e. it will cause compilation to fail if you use a message ID not present
//    in the l10n json file.

export type L10nMessages = typeof enUSMessages;

export interface L10nProviderProps extends IntlProvider.Props {
  messages: L10nMessages;
}
export const L10nProvider: React.SFC<L10nProviderProps> = props => {
  return <IntlProvider textComponent={React.Fragment} {...props} />;
};

export interface LocalizedMessageProps extends FormattedMessage.Props {
  id: keyof L10nMessages;
}
export const LocalizedMessage: React.SFC<LocalizedMessageProps> = props => {
  return <FormattedMessage {...props} />;
};

Я видел несколько ответов на те же вопросы, и он предлагает мне обернуть компонент с помощью injectIntl ​​(React-Intl), чтобы вставить необработанную строку, хотя и дает мне эту ошибку,снимок экрана прилагается. enter image description here

Чтобы лучше объяснить проблему, вот еще некоторые детали компонента.

Вот компонент contactContainer:

export class ContactContainer extends React.Component<ContactContainerProps, ContactContainerState> {  


  constructor(props: ContactContainerProps) {
    super(props);
    this.state = this.getInitialState();
  }

  getInitialState() {
    const me = (this.props.account.me)
      ? this.props.account.me
      : emptyProfile;

    const contactForm: OvationsPortalApi.Types.ContactForm = {
      firstName: me.firstName || '',
      lastName: me.lastName || '',
      email: me.preferredEmail || '',
      phone: me.phoneNumber || '',
      contactMethod: me.preferredContactMethod || OvationsApi.Enums.NotificationChannelType.None,
      questionCategory: '',
      message: '',
    };


  }

  render() {
    return (
      <Container className="py-4">

                    <Col md={6}>
                      <div className="mb-3">
                        <Label for={elements.contactUs.id.contactMethod}>
                          <LocalizedMessage id="best_contact_method" />
                        </Label>
                        <Input
                          type="select"
                          id={elements.contactUs.id.contactMethod}
                          name="contactMethod"
                          required
                          onChange={this.onInputChange}
                        >
                          <option value=""><LocalizedMessage id="please_select" /></option>
                          {Object.keys(ContactMethods).map(key => (
                          <option key={key} value={ContactMethods[key]}>
                            {ContactMethods[key]}
                          </option>
                        ))}
                        </Input>

      </Container>
    );
  }
}

export default connect(/* istanbul ignore next */state => state)
(withData(contactLoader)(injectIntl(ContactContainer)));

Вот компонент containerProps:

import S from 'redux-modules/definitions/RootState';
import { Dispatch } from 'react-redux';
import { RouteComponentProps } from 'react-router';

interface ContainerProps<P = {}> extends RouteComponentProps<P> {}
interface ContainerProps<P = {}> extends S {}
interface ContainerProps<P = {}> {
  dispatch: Dispatch<S>;
}

export type ProgramContainerProps = ContainerProps<{ clientId: string; programId?: string; }>;

export default ContainerProps;

вот пары ключ-значение для formattedMessage id:

{
  "please_select": "Please select",
  "question_category_required": "Question category is required.",
  "message": "Message",
  "message_required": "Message is required.",
  "submitting": "Submitting..."
}

Пожалуйста, посмотрите и предложите хорошее решение.Спасибо за ваше время!

...