【问题标题】:String Interpolation in React component with strings returned from server使用从服务器返回的字符串在 React 组件中进行字符串插值
【发布时间】:2016-06-05 17:11:19
【问题描述】:

我目前有从服务器返回的字符串,其中包含需要在前端插入的变量。我正在使用 React 和 Redux 并将字符串设置为组件的 props,以便按如下方式访问它们:

this.props.translations['hello-message']

示例字符串如下所示:

Hello, ${name}!

此外,我还从服务器返回了用户名,并将其设置为 props。如何插入字符串,以便用户名出现在字符串中,从而出现在渲染的 React 组件中。

我尝试在 React 组件的渲染中使用 String.prototype.replace() 方法,如下所示:

let helloMessage = this.props.translations['hello-message'].replace('${name}', 'Joe');

但这会返回错误:“未捕获的类型错误:无法读取未定义的属性‘替换’”。我尝试了各种其他策略,例如 componentWillReceiveProps() 中的函数或创建此处提到的辅助函数:How can I construct a Template String from a regular string? all 无济于事。

【问题讨论】:

    标签: javascript string reactjs ecmascript-6


    【解决方案1】:

    该错误消息意味着this.props.translations['hello-message'] 不包含您认为的值。这可能是一个反应问题,您的代码在从 Redux 存储中提取数据时多次调用此部分,并且在第一次调用时 var 尚未初始化。

    作为一个非常简单的解决方案,尝试包装该语句并检查变量是否存在;

    let helloMessage = '';
    if(this.props.translations['hello-message']){
        helloMessage = this.props.translations['hello-message'].replace('${name}', 'Joe');
    }
    

    【讨论】:

    • 呃……如此简单,但完美!非常感谢!!
    • 很高兴能帮上忙。如果它解决了您的问题,请务必将答案标记为正确,以便其他人不需要进入线程。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 2014-08-24
    • 2017-08-03
    • 2023-02-10
    • 1970-01-01
    相关资源
    最近更新 更多