如何在i18next中遍历并渲染字符串/对象数组?
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

