You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RTK Reselect中TypeScript报错:'state'已声明但未使用的解决方法

RTK记忆化选择器的TypeScript未使用变量报错解决

问题场景

在RTK切片中定义了如下记忆化全局选择器:

export const selectPostsByUser = createSelector(
  [selectAllPosts, (state, userId: number) => userId],
  (posts, userId) => posts.filter((post) => +post.user === userId),
);

在组件中调用时:

const postsForUser = useAppSelector((state) => selectPostsByUser(state, userId));

触发TypeScript报错:'state' is declared but its value is never read,但如果只传userId,createSelector不会将其视为输入选择器,疑惑为何必须带上state以及如何解决报错。

原因说明

RTK的createSelector生成的选择器函数必须以Redux state作为第一个参数,这是它的核心设计规则——输入选择器的职责是从state中提取数据,即便你需要传递自定义参数(比如userId),也得保留state参数来匹配选择器的函数签名,否则createSelector无法正确识别输入依赖并完成记忆化逻辑。

解决方法

方法1:用下划线标记未使用的state变量

TypeScript允许用_作为变量名,表示该变量是故意不使用的,直接修改组件中的调用代码即可:

const postsForUser = useAppSelector((_state) => selectPostsByUser(_state, userId));

方法2:将选择器改造成柯里化形式

把选择器改成先接收自定义参数(userId),再返回一个接收state的选择器函数,这样调用时更简洁,也彻底避免未使用变量的问题:

改造后的选择器代码:

export const selectPostsByUser = (userId: number) => 
  createSelector(
    [selectAllPosts],
    (posts) => posts.filter((post) => +post.user === userId)
  );

组件中的调用方式:

const postsForUser = useAppSelector(selectPostsByUser(userId));

这种方式下,useAppSelector会自动把Redux state传递给柯里化后返回的选择器函数,既符合RTK的设计逻辑,也消除了TypeScript报错。

内容的提问来源于stack exchange,提问作者Владимир Шустров

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 20:47:09