react.js - javascript中如何用占位符定義restful那種url啊, angular我知道, 但是用react該用哪個庫?
問題描述
我知道angular里面的是這樣的
$resource(’http://localhost:8080/web/user/:id/oper/:active’,{id: ’111’,active: ’y’})
react里面用啥呢, 是否有什么包可以實現這個功能呢
問題解答
回答1:我用 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]; });};回答2:
自己寫了一個,
/** * 格式化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;};
