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

React v6中替换withRouter与History的社交媒体项目实现方法

React Router v5 转 v6:替换withRouter和History的修改方案

一、修改CreateProfile.js文件

1. 替换路由相关导入

移除withRouter,导入useNavigate钩子,同时把页面内的跳转链接从原生<a>换成Link组件:

import React, { Fragment, useState } from 'react';
// 移除withRouter,新增useNavigate
import { Link, useNavigate } from 'react-router-dom';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { createProfile } from '../../actions/profile';

2. 替换history为navigate钩子

在组件内部通过useNavigate获取导航函数,替代之前通过withRouter注入的history:

const CreateProfile = ({ createProfile }) => {
  // 新增这行,获取navigate函数
  const navigate = useNavigate();

  // ... 原有的state和onChange逻辑保持不变

  const onSubmit = e => {
    e.preventDefault();
    // 把history换成navigate
    createProfile(formData, navigate);
  }

  // ... 其他代码不变,注意修改下面的返回部分的Go Back链接
}

3. 修复页面内跳转链接

把原有的<a>标签换成Link组件,避免页面刷新:

// 原代码:
// <a className="btn btn-light my-1" href="dashboard.html">Go Back</a>

// 修改为:
<Link className="btn btn-light my-1" to="/dashboard">Go Back</Link>

4. 移除withRouter包装

v6中connect高阶组件不需要再用withRouter包裹,直接导出即可:

// 原代码:
// export default connect(null, { createProfile })(withRouter(CreateProfile));

// 修改为:
export default connect(null, { createProfile })(CreateProfile);

二、修改actions/profile.js文件

1. 替换history.push为navigate函数

v6中navigate是直接调用的函数,替代history.push:

// Create or update profile
export const createProfile = (formData, navigate, edit = false) => async dispatch => {
  try {
    // 修复拼写错误:Contet-Type → Content-Type
    const config = {
      headers: {
        'Content-Type': 'application/json'
      }
    }

    const res = await axios.post('/api/profile', formData, config);

    dispatch({
      type: GET_PROFILE,
      payload: res.data
    });

    dispatch(setAlert(edit ? 'Profile Updated' : 'Profile Created'));

    if(!edit) {
      // 替换history.push为navigate
      navigate('/dashboard');
    }
  } catch (err) {
    // ... 原有错误处理逻辑不变
  }
}

2. 修复请求头拼写错误

原代码中'Contet-Type'少写了一个n,改为'Content-Type',避免请求格式错误。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 05:06:28