是否可以使用React Router重定向到默认的URL哈希?

问题描述 投票:1回答:2

我正在使用React Router 5。

我有一条路径/item/:id。当我导航到该路径时,我希望能够使用默认的哈希标识符加载页面。 i.e. /item/:id#123

关于更多上下文,我在页面上有与项目相关联的步骤列表。每次用户选择一个不同的步骤时,哈希值都会发生相应的变化,如下所示:

step 1 -> /item/123#1
step 2 -> /item/123#2
step 3 -> /item/123#3

这是我的组件代码的粗略实现:

import { withRouter } from 'react-router-dom'
import steps from './steps'

const ItemPage = ({ history, location }) => {
  const { hash, pathname } = location
  const changeURLhash = idx => {
    history.push({ pathname: pathname, hash: idx.toString() })
  }

  return (
    <ul>
      {steps.map(step => (
        <li key={i} onClick={changeURLhash}>
          {step.title}
        </li>
      ))}
    </ul>
  )
}

我可以选择一个步骤后更改哈希值,但是在初始页面加载时,如果没有单击任何内容,但url路径中没有哈希值。我需要更改此设置,因为默认情况下在页面加载时选择了第1步。

什么是最好的方法?预先感谢!

reactjs react-router url-routing react-router-dom browser-history
2个回答
1
投票

无法看到您的代码,很难为您的问题提供准确的解决方案。但是,我为您创建了一个沙箱,以演示如何执行此操作。

https://codesandbox.io/s/gifted-sinoussi-5eomb

基本上,Item组件需要useStateuseEffect的组合

import React, { useState, useEffect } from "react";

const Item = ({ steps }) => {
  const [currentStep, setCurrentStep] = useState(1);

  useEffect(() => {
    const path = window.location.href;
    const step =
      path.indexOf("#") !== -1 ? path.slice(path.indexOf("#") + 1) : "";
    if (step) {
      setCurrentStep(step);
    }
  }, []);

  const handleOnClick = step => {
    setCurrentStep(step);
  };

  const createSteps = () => {
    return steps.map((step, index) => {
      return (
        <div
          className={step == currentStep ? "currentStep" : "step"}
          key={index}
          onClick={() => handleOnClick(step)}
        >
          <h4>Step: {step}</h4>
          <input />
        </div>
      );
    });
  };
  return <div>{createSteps()}</div>;
};

export default Item;

您有一个状态来跟踪当前步骤。还有一个标记创建器功能,用于将突出显示的类应用于活动项目。然后,在useEffect()中,您只需提取步骤号(#后面的字符)并将状态设置为该值。这将重新渲染组件,然后您的标记创建者会将类应用于该步骤。


0
投票

我已经能够通过在useEffect挂钩中使用history.replace解决此问题。

当页面加载且URL中没有哈希标识符时,我将历史记录堆栈中的当前路径替换为包含默认哈希的新路径

useEffect(() => {
  if (!hash) history.replace({ pathname: pathname, hash: '0' })
}, [hash, history, pathname])
© www.soinside.com 2019 - 2024. All rights reserved.