无法找到匹配history.push()的正确AST选择器
解决ESLint禁止history.push调用的选择器问题
你之前的选择器无效,是因为对history.push()的AST结构判断有误:history.push对应的AST节点是MemberExpression,其中object字段指向name为"history"的Identifier节点,property字段指向name为"push"的Identifier节点,二者并非相邻兄弟节点,所以用相邻兄弟选择器+无法匹配。
正确的配置方式是直接匹配对应的MemberExpression节点,在ESLint配置文件中修改no-restricted-syntax规则:
{ "rules": { "no-restricted-syntax": [ "error", { "selector": "MemberExpression[object.name='history'][property.name='push']", "message": "请勿使用history.push,请改用React Router v6的useNavigate钩子" } ] } }
如果需要同时禁止history.replace、history.goBack等其他历史记录操作,可以用正则匹配方法名:
{ "rules": { "no-restricted-syntax": [ "error", { "selector": "MemberExpression[object.name='history'][property.name=/^(push|replace|goBack)$/]", "message": "请勿使用history相关方法,请改用React Router v6的useNavigate钩子" } ] } }
内容的提问来源于stack exchange,提问作者Vier
相关产品推荐
相关产品推荐

