React.js – Wie verwende ich Platzhalter, um Restful-URLs in Javascript zu definieren? Ich kenne mich mit Angular aus, aber welche Bibliothek sollte ich verwenden, wenn ich React verwende?
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-07-05 11:00:33
0
2
1216

Ich weiß, dass es im Winkel so ist

$resource('http://localhost:8080/web/user/:id/oper/:active',{id: '111',active: 'y'})

Was wird in React verwendet? Gibt es ein Paket, das diese Funktion erreichen kann?

曾经蜡笔没有小新
曾经蜡笔没有小新

Antworte allen(2)
学习ing

我用 http://localhost:8080/web/user/{id}/oper/{active} 这样形式的,和后台 SpringMvc 的 URL 形式一样,字符串替换的方法用下面的函数

/**
 * 扩展了 String 类型,给其添加格式化的功能,替换字符串中 {placeholder} 或者 {0}, {1} 等模式部分为参数中传入的字符串
 * 使用方法:
 *     'I can speak {language} since I was {age}'.format({language: 'Javascript', age: 10})
 *     'I can speak {0} since I was {1}'.format('Javascript', 10)
 * 输出都为:
 *     I can speak Javascript since I was 10
 *
 * @param replacements 用来替换 placeholder 的 JSON 对象或者数组
 */
String.prototype.format = function(replacements) {
    replacements = (typeof replacements === 'object') ? replacements : Array.prototype.slice.call(arguments, 0);
    return formatString(this, replacements);
}
/**
 * 替换字符串中 {placeholder} 或者 {0}, {1} 等模式部分为参数中传入的字符串
 * 使用方法:
 *     formatString('I can speak {language} since I was {age}', {language: 'Javascript', age: 10})
 *     formatString('I can speak {0} since I was {1}', 'Javascript', 10)
 * 输出都为:
 *     I can speak Javascript since I was 10
 *
 * @param str 带有 placeholder 的字符串
 * @param replacements 用来替换 placeholder 的 JSON 对象或者数组
 */
var formatString = function (str, replacements) {
    replacements = (typeof replacements === 'object') ? replacements : Array.prototype.slice.call(arguments, 1);
    return str.replace(/\{\{|\}\}|\{(\w+)\}/g, function(m, n) {
        if (m == '{{') { return '{'; }
        if (m == '}}') { return '}'; }
        return replacements[n];
    });
};
黄舟

自己写了一个,

/**
 * 格式化url占位符
 * eg: http://localhost:8080/yunpan/{id}/aaa/{name}
 * urlFormat(url, {id: '111', name: 'yc'})
 * => http://localhost:8080/yunpan/111/aaa/yc
 *
 * @param url
 * @param param
 * @returns {*}
 */
export const urlFormat = (url, param) => {
    if (param === undefined || param === null || param === {}) {
        return url;
    }

    let keys = Object.keys(param);
    for (let key of keys) {
        url = url.replace(new RegExp("\\{" + key + "\\}", "g"), param[key]);
    }
    return url;
};
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!