reactjs - 输入问题 URLSearchParams
问题描述
我有这个代码:
const paramsString = "q=URLUtils.searchParams&topic=api";
const searchParams = new URLSearchParams(paramsString);
const Search: string = searchParams.get("topic")?
searchParams.get("topic"):"100";
我收到此错误:
Type 'string | null' is not assignable to type 'string'.
Type 'null' is not assignable to type 'string'.
解决方案
更新:只需将参数值存储在变量中(TypeScript 没有为函数调用实现基于控制流的类型分析):
const topic = searchParams.get("topic");
const Search: string = topic ? topic : "100";
那是因为如果没有找到搜索参数则URLSearchParams.get()
返回null
,所以searchParams.get("Search")
可以是null
.
您strictNullChecks
启用了编译器选项,因此出现错误。
要解决此问题,您可以将变量键入为string | null
:
const Search: string | null = searchParams.get("topic")
? searchParams.get("Search")
: "100";
或者,如果您确定查询字符串具有“搜索”参数,则可以使用非空断言运算符:
const Search: string = searchParams.get("topic")
? searchParams.get("Search")!
: "100";
推荐阅读
- java - netbeans找不到maven项目
- view - Flutter:bloc,如何显示警报对话框
- reactjs - 样式不能通过样式化组件起作用
- linux - 在mac中递归选择文件 - 需要更漂亮的目录中的所有文件
- c# - 自定义卸载不删除 .net 应用程序中的文件
- r - Change background color with plot_grid
- c# - 在c#中保存datagridview中的数据
- javascript - 防止将具有相同值的对象添加到数组的简单方法
- continuous-integration - 这项工作被卡住了,因为该项目没有在线分配任何跑步者。进入跑步者页面
- jasper-reports - 饼图显示的键值错误