ReactJS:react-router-dom的redirect函数无法正常工作
解决React Router类组件跳转无效的问题
问题根源
你直接调用的redirect是react-router-dom提供的组件,不是可执行函数,所以redirect(url)这种写法完全不会触发页面跳转,这是核心问题。
类组件的两种解决方案
因为类组件无法使用useHistory钩子,你可以通过以下两种方式实现跳转:
方案1:直接使用路由注入的history props
如果你的组件是通过<Route>直接渲染的(比如配置在component或render属性中),组件会自动接收history、location、match这三个props,直接调用history.push()即可跳转:
修改你的函数:
switchView = () => { this.setState((state) => { const newSignupState = !state.signup; const url = newSignupState ? '/signin' : '/signup'; // 直接使用props里的history this.props.history.push(url); return { signup: newSignupState }; }); }
方案2:用withRouter高阶组件包裹组件
如果你的组件没有被<Route>直接渲染,无法拿到路由相关props,就用withRouter把组件包裹起来,它会把路由props注入到你的组件中:
- 先导入
withRouter:
import { withRouter } from "react-router-dom";
- 包裹你的组件(比如你的组件叫
AuthSwitch):
export default withRouter(AuthSwitch);
- 之后就可以像方案1一样,在组件里使用
this.props.history.push(url)来跳转了。
额外注意点
更规范的写法是在setState的第二个回调里执行跳转,确保状态更新完成后再触发页面跳转:
switchView = () => { this.setState((state) => ({ signup: !state.signup }), () => { // 状态更新完成后执行跳转 const url = this.state.signup ? '/signin' : '/signup'; this.props.history.push(url); }); }
内容的提问来源于stack exchange,提问作者Ylann
相关产品推荐
相关产品推荐

