You need to enable JavaScript to run this app. react-router-dom v5中Link正常但Redirect、history.push仅更新URL不渲染组件
优惠活动
大模型
产品
解决方案
定价
更多

react-router-dom v5中Link正常但Redirect、history.push仅更新URL不渲染组件

React Router 路由跳转异常问题记录

编辑补充:我十分惭愧地说明,问题的根源是我在传给Redirect和history.push的URL中存在拼写错误。因此给各位参考:正常情况下Link、Redirect与history.push的路由跳转表现应当完全一致。


问题描述

为何Link可以完成完整的路由跳转渲染,而Redirect与history.push仅会更新浏览器地址栏的URL,不会渲染对应URL匹配的组件?

期望实现的业务流程

  • 用户点击按钮,通过Redux action creator调用服务端函数
  • 服务端函数将数据写入Firebase Firestore
  • 服务端函数返回新建文档的ID,action creator使用该ID通过history.push跳转到指定URL,在前端渲染展示该新建文档的页面

实际运行效果

浏览器地址栏显示了正确的URL,但未渲染预期的组件。我做了对照测试:硬编码Redirect与Link跳转到同一URL,只有Link能正常完成组件渲染。

已尝试的排查方案

  • 分别使用BrowserRouter、Router、HashRouter三种路由组件测试
  • 调整路由组件的挂载位置:分别尝试将所选路由组件放在App组件外层、以及App组件内部紧邻根节点的位置
  • 使用useHistory()获取history实例,并将其从业务组件传入action creator
  • 自定义history配置文件,将其传入Router组件,再在action creator文件中引入该实例

相关代码实现

index.js 入口文件

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

import { Router } from 'react-router-dom'
import history from './config/history'

// firebase 和 redux store 配置代码已省略

ReactDOM.render(
  <Provider store={store}>
    <ReactReduxFirebaseProvider {...rrfProps}>
      <Router history={history} >
        <App />
      </Router>
    </ReactReduxFirebaseProvider>
  </Provider>,
  document.getElementById('root')
);

自定义history配置文件

import { createBrowserHistory } from 'history'
const history = createBrowserHistory()
export default history;

业务调用的action creator文件

import history from '../../config/history'

export const importWebsite = (data) => {
  return (dispatch, getState, { getFirebase }) => {
    const firebase = getFirebase()
    const profile = getState().firebase.profile
    const userId = getState().firebase.auth.uid

    data = {
      ...data,
      userFirstName: profile.firstName,
      userLastName: profile.lastName,
      username: profile.username,
      userId: userId,
    }
    const pull_website = firebase.functions().httpsCallable('pull_website')
    pull_website(data)
      .then((res) => {
        dispatch({ type: 'IMPORT_SUCCESS' })
        history.push('/websites/' + res.data.id)
      }).catch((err) => {
        dispatch({ type: 'IMPORT_FAIL', err })
      })
  }
}

内容的提问来源于stack exchange,提问作者bront

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.23 22:15:03