简体   繁体   中英

State changes in the react native functional component

I want the Calender changes its language depends on the user language (there are 3 languages can be chosen in the app, English Spanish and Italian), English is the default language of the calendar library. Btw the library uses moment.js to use different languages. But the calender language is not changed when I change the user language. I need to help to fix this

import { Moment } from 'moment';
import React, { FunctionComponent, useContext, useEffect } from 'react';
import { NETWORK_ONLY, useQuery } from 'relay-hooks';
import { AuthenticationContext } from '../providers/authentication/AuthenticationProvider';
import CalendarStrip from 'react-native-calendar-strip';
import moment from 'moment';

import USER_BY_ID, {
  relayGetUserByIdQuery,
} from '../__generated__/relayGetUserByIdQuery.graphql';
interface Props {
  selectedDate: Date | Moment;
  setSelectedDate: React.Dispatch<React.SetStateAction<Date | Moment>>;
}

const WeeklyCalendar: FunctionComponent<Props> = (props) => {
  const { selectedDate, setSelectedDate } = props;
  const { userData, refreshQuery } = useContext(AuthenticationContext);

  const { data } = useQuery<relayGetUserByIdQuery>(
    USER_BY_ID,
    { id: userData?.userId || ''},
    { fetchPolicy: NETWORK_ONLY }
  );

  // The localization rules are the same as moments for adding localization to react-native-calendar-strip component
  useEffect(() => {
    refreshQuery();
    if (data?.user?.language == 'ES') {
      require('moment/locale/es');
    }
    if (data?.user?.language == 'IT') {
      require('moment/locale/it');
    }
  }, [data?.user?.language])

  return (
    <CalendarStrip
      scrollable
      style={{ height: 75 }}
      calendarHeaderStyle={{
        color: '#3D3D3D',
        fontSize: 16,
        fontWeight: '500',
      }}
      dateNumberStyle={{ color: '#3D3D3D' }}
      dateNameStyle={{ color: '#3D3D3D' }}
      highlightDateNumberStyle={{ color: 'white' }}
      highlightDateNameStyle={{ color: 'white' }}
      highlightDateContainerStyle={{
        borderRadius: 10,
      }}
      iconContainer={{ flex: 0.1 }}
      numDaysInWeek={7}
      daySelectionAnimation={{
        type: 'background',
        duration: 200,
        highlightColor: '#2975D6',
      }}
      selectedDate={selectedDate}
      onDateSelected={(date) => setSelectedDate(date)}
    />
  );
};

export default WeeklyCalendar;

Please go to your index.js and import the specific "Locale" after the main moment import

import 'moment';
import 'moment/locale/fr';  // language must match config
import 'moment/min/locales'

and set you moment with

data?.user?.language == 'ES' ? moment.local('ES') : moment.local('IT')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM