You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在i18next中遍历并渲染字符串/对象数组?

How to Render an Array from i18n Resources in React Native FlatList

The issue you’re hitting is that i18next defaults to returning string values—so when you call t('home:data'), it’s converting your array into a string instead of passing through the actual array object. Here’s how to fix it:

Step 1: Use the useTranslation hook properly

First, make sure you’re importing and using the hook to get access to the translation function in your component:

import { useTranslation } from 'react-i18next';
import { FlatList, Text } from 'react-native';

const YourComponent = () => {
  const { t } = useTranslation();
  
  // Fetch the array with returnObjects: true to get the actual array
  const data = t('home.data', { returnObjects: true }); // Use 'home:data' if your separator is set to colon
  
  return (
    <FlatList
      data={data}
      keyExtractor={(item) => item.id.toString()} // Prefer item.id over index for stable keys
      renderItem={({ item }) => <Text>{item.val}</Text>}
    />
  );
};

export default YourComponent;

Key Fix: returnObjects: true

The critical addition here is the returnObjects: true option in your t() call. This tells i18next to return the raw array/object from your resources instead of converting it to a string—exactly what you need to feed into FlatList’s data prop.

Double-check your i18n separator

Make sure the key you use in t() matches your i18n config’s separator. By default, i18next uses a dot (.) to separate namespaces and keys, so t('home.data') is correct unless you explicitly set nsSeparator: ':' in your init options.

For Class Components (if you’re using them)

If you’re working with a class component instead of functional, use the withTranslation HOC:

import { withTranslation } from 'react-i18next';
import { FlatList, Text } from 'react-native';

class YourComponent extends React.Component {
  render() {
    const { t } = this.props;
    const data = t('home.data', { returnObjects: true });
    
    return (
      <FlatList
        data={data}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({ item }) => <Text>{item.val}</Text>}
      />
    );
  }
}

export default withTranslation()(YourComponent);

This should let you properly iterate over and render each item from your i18n array in the FlatList.

内容的提问来源于stack exchange,提问作者alfredopacino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:18:28