React-Intl:从API响应中加载新字符串
问题描述:
我有一个组件需要来自后端的字符串。我目前请求服务器上的.po
文件,将其转换为.json
并将其返回给我的React组件。然后,我希望能够同时在字符串中替换正确的值显示这些字符串,即React-Intl:从API响应中加载新字符串
<FormattedMessage id={dynamicId} values={dynamicVals} />
dynamicId从单独的API调用拉动,以及dynamicVals。
我的问题是,这些字符串没有像我所有的其他应用程序字符串捆绑在一起,所以react-intl
是不知道他们。如何将这些字符串添加到库客户端/异步?我试图使用defineMessages
和addLocaleData
,但我要么做的不正确,要么没有使用正确的API方法。 addLocaleData
提供了将字符串添加到库的方法吗?这可能吗?
总结:
我怎样才能收到
{
notifications.friendships.nowfriends: "{name} is now your friend"
}
从API,并使用它显示:
<FormattedMessage id='notifications.friendships.nowfriends' values={{ name: 'StackOver Bro' }} />
感谢提前的帮助。
答
如果有人想知道什么,我终于实现了......
因为我已经有字符串和变量与插值,我绕过了本地化库,只是使用了以下功能(感谢在这个question答案,尤其是@ user2501097和@Bryan雷纳)
/**
* see: https://*.com/questions/29182244/convert-a-string-to-a-template-string
*
* Produces a function which uses template strings to do simple interpolation from objects.
*
* Usage:
* var makeMeKing = generateTemplateString('${name} is now the king of {country}!');
*
* console.log(makeMeKing({ name: 'Bryan', country: 'Scotland'}));
* // Logs 'Bryan is now the king of Scotland!'
*/
const generateTemplateString = (function() {
const cache = {}
function generateTemplate(template) {
let fn = cache[template]
if (!fn) {
// Replace ${expressions} (etc) with ${map.expressions}.
const sanitized = template
.replace(/\$?\{([\s]*[^;\s\{]+[\s]*)\}/g, (_, match) => {
return `\$\{map.${match.trim()}\}`
})
// Afterwards, replace anything that's not ${map.expressions}' (etc) with a blank string.
.replace(/(\$\{(?!map\.)[^}]+\})/g, '')
fn = Function('map', `return \`${sanitized}\``)
cache[template] = fn
}
return fn
}
return generateTemplate
}())
export default generateTemplateString
你有没有尝试过,当然'ID = {notifications.friendships.nowfriends}' – bennygenel
是的。但是react-intl没有对该id的任何引用。我想知道如何将字符串添加到反应组件中的库中,我在该API中调用并显示字符串 – jacoballenwood
我之前没有使用该库,所以我只是猜测。你可以使用['addlocaledata'](https://github.com/yahoo/react-intl/wiki/API#addlocaledata)与你的API调用的结果吗?或['definemessages'](https://github.com/yahoo/react-intl/wiki/API#definemessages) – bennygenel