json - 从服务器获取我的应用程序的文本
问题描述
我想用来自服务器的文本更改我的应用程序中的所有静态文本,因此我必须获取此文本LoadingScreen
,然后将其导出以在其他屏幕中使用
<Text>My products</Text>
到 <Text>{constants.myProduct}</Text>
从 LoadingScreen 导入常量之后
如何将 json 响应导出LoadingScreen
到所有其他 Screen ?还有另一种方法吗?PS。我不使用Redux
解决方案
最简单但不是最好的方法就是使用所有文本键创建和导出变量。例如:
// 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
函数
推荐阅读
- reactjs - MIME 类型错误 - 将 React 应用程序部署到 Heroku
- javascript - react 组件在使用 useEffect 时会渲染多次
- javascript - 过滤 JSON 对象 Javascript/Node.js 的函数
- javascript - 如何在单独的 js 文件中将按钮单击转换为 mouseup 事件
- python - 读取 Parquet 文件比预期慢
- python - 如何将数组加载为数据框中的新列?
- java - 我的简单 build.gradle 设置有什么问题?
- java - 如何使用 setAutoCreateColumnsFromModel(false) 从 TableModel 和 TableColumnModel 中删除 JTable 列?
- django - 为什么命令提示符返回 gdal not found 错误
- angular - Ionic 3 subscribe 多次触发