如何在React中传递多个参数并作为查询参数发送给API
你现有代码存在3个影响参数传递的问题
- 变量大小写不匹配:函数入参定义为
page、pageSize,URL拼接时错误写为Page、PageSize,会导致参数值为undefined - URL拼接格式错误:
?后多了多余空格,会导致服务端无法正确识别filter参数 - 缺少参数编码:如果参数包含特殊字符(中文、&、=、空格等)会导致查询串解析失败
修复方案
方案1:修正原拼接写法
手动修正拼写问题,同时对参数做URL编码:
getScoreboardInfo: (title,pageSize,page,sort,callback) => { const filter = `title@=${title}` return Service.get(`scoreboard/getinfos?filter=${encodeURIComponent(filter)}&sort=${encodeURIComponent(sort)}&page=${encodeURIComponent(page)}&pageSize=${encodeURIComponent(pageSize)}`, (status, data) => { callback(status, data); }); },
方案2:使用URLSearchParams(更推荐,避免拼写和编码问题)
通过内置的URLSearchParams构造查询串,自动处理编码和格式:
getScoreboardInfo: (title,pageSize,page,sort,callback) => { const filter = `title@=${title}` const queryParams = new URLSearchParams({ filter, sort, page, pageSize }) return Service.get(`scoreboard/getinfos?${queryParams.toString()}`, (status, data) => { callback(status, data); }); },
方案3:如果你的Service.get支持传入参数对象
多数封装的请求库支持直接传入查询参数对象,不需要手动拼接:
getScoreboardInfo: (title,pageSize,page,sort,callback) => { const filter = `title@=${title}` return Service.get("scoreboard/getinfos", { filter, sort, page, pageSize }, (status, data) => { callback(status, data); }); },
注:此处参数传递的具体写法以你使用的Service请求库的官方规范为准
内容的提问来源于stack exchange,提问作者zahra zamani
相关产品推荐
相关产品推荐

