如何在使用 react-router-dom 时通过浏览器后退按钮关闭模态框?

9

我正在使用react-router-dom,我希望能在点击浏览器返回按钮时关闭模态框。

此外,在我的场景中,模态框组件不是Switch的一部分。那么我该如何关闭模态框呢?

谢谢提前。:)


请提供一些代码。 - Owais Latif
@OwaisLatif 对不起,我不能这样做,因为它们都很分散。我的问题与此问题非常相似 - https://dev59.com/7azla4cB1Zd3GeqPFPQx - Shubham Bisht
3个回答

4
你可以使用类似这样的方法来检测“返回”按钮的按下。
componentDidUpdate() {
  window.onpopstate = e => {
    
  }
}

然后,根据您的模态框(Bootstrap或其他)的不同,您可以调用.hide().close()


1
那么当我关闭模态框时,如何在这种情况下禁用返回按钮? - Shubham Bisht
你是指相反的方向吗?你需要知道(在你的状态下)模态框是否关闭,当“onpopstate”再次触发时,你可以使用e.preventDefault()。但它可能无法在每个浏览器中正常工作。 - sotirelisc
不,我的意思是当我按浏览器的返回按钮时,我希望模态框关闭而不是返回到上一个屏幕。 - Shubham Bisht

0

我已经制作了一个简单的钩子,叫做useAppendLocationState,它可以完成所有工作:

function SomeComponent() {
    const [showModal , appendShowModal ] = useAppendLocationState('showModal');

    return (
        <div>
            <div>...some view...</div>
            <button onClick={() => appendOpenModal(true)}>open modal</button>
            {showModal && <SomeModal closeHandler={() => window.history.back()} />}
        </div>
    )
}

useAppendLocationState 返回一个数组,就像 useState 一样,第一个条目是来自浏览器位置状态的状态属性值,第二个条目是将新项目推送到浏览器历史记录的方法,并将新状态属性附加到当前位置状态。

这是我们的useAppendLocationState定义:

import { useHistory } from 'react-router';

export function useAppendLocationState(key) {
    if (!key) throw new Error("key cannot be null or empty value")

    const history = useHistory()
    const currentLocationState = history.location.state;

    const appendStateItemValue = (value) => {
        const newLocationState = { ...currentLocationState }
        newLocationState[key] = value;
        history.push(history.location.pathname, newLocationState)
    }

    const stateItemValue = history.location.state && history.location.state[key]


    return [stateItemValue, appendStateItemValue]
}

export default useAppendLocationState

我自己也使用过类似的解决方案,但它也有几个缺点。例如:用户打开 /home,然后打开 /home#yourmodal,最后关闭了网站。下一次他们从历史记录中打开该页面 /home#yourmodal 时,他们将不再看到模态框,或者如果该键存在于另一个页面(例如 /login#yourmodal),则属性会丢失。 - Kristi Jorgji

-7
你试过了吗:ComponentWillUnmount?

1
如何使用ComponentWillUnmount? - Shubham Bisht

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接