首页 > 解决方案 > 从服务器获取我的应用程序的文本

问题描述

我想用来自服务器的文本更改我的应用程序中的所有静态文本,因此我必须获取此文本LoadingScreen,然后将其导出以在其他屏幕中使用

<Text>My products</Text><Text>{constants.myProduct}</Text>从 LoadingScreen 导入常量之后

如何将 json 响应导出LoadingScreen到所有其他 Screen ?还有另一种方法吗?PS。我不使用Redux

标签: jsonreact-native

解决方案


最简单但不是最好的方法就是使用所有文本键创建和导出变量。例如:

// text.utils.js 
let _textData;

export const loadTextData = () => fetch(YOUR_SERVER)
 .then((r) => r.json())
 .then(r => _textData = r);

export const getTextData = (key, defaultValue) => _textData[key] || defaultValue;

// init inside App or something else
import {loadTextData} from 'text.utils.js';

componentDidMount() {
  loadTextData();
}

// inside components
import {getTextData} from 'text.utils.js';

const myProductText = getTextData('myProduct', 'This is product text');
const myProductCountText = getTextData('myProductCount', 'This is product count text');

<Text>{myProductText}</Text>
<Text>{myProductCountText}</Text>

PS 这不是反应的好解决方案。最好的选择是创建一个上下文或钩子,它将为您的组件提供字符串。此外,如果您的字符串对象有嵌套对象,您可以重新组织getTextData函数


推荐阅读