【问题标题】:Modal not appearing on refresh模式没有出现在刷新
【发布时间】:2020-12-12 19:12:30
【问题描述】:

当用户单击产品时,我正在使用 material-ui 并使用 redux 渲染模式,效果很好。现在我正在尝试使用 react-router v6 添加路由。

App.jsx

export default function App() {
return (
        <>
            <CssBaseline />
            <AppBar>
                <Routes>
                    <Route path="/" element={<Home />} />
                    <Route path="/:productType" element={<FoodDrink />} />
                    <Route path="/:productType/:category" element={<ResultsList />}>
                        <Route path=":brandproduct" />
                    </Route>
                </Routes>
            </AppBar>
            <ProductModal />
        </>
);
}

&lt;FoodDrink /&gt;&lt;ResultsList /&gt; 组件呈现出色并可以正常导航。

当我点击一个结果时,它会打开带有 redux 的模式。

ResultsList.jsx

function handleResultClick() {
    onToggleProductModal();
}

结果卡中指向产品模式的链接会生成正确的 URL。

Result.jsx

<>
        <Card
            component={Link}
            to={`${toKebabCase(props.brand)}-${toKebabCase(props.name)}`}
            onClick={props.clicked} // this calls handleResultClick in the parent, ResultsList.jsx
        >
            {cardContent}
        </Card>
        <Outlet />
    </>

当模式关闭时,URL 会按原样返回到 ResultsList 上的类别。 (我知道 navigate(-1) 可能不是最好的方法,但我认为现在还可以)。

ProductModal.jsx

const onCloseModal = () => {
    props.onToggleProductModal();
    navigate(-1);
};

问题是手动导航到相同的 URL 不会打开模态,并且在打开模态的情况下刷新页面会加载没有打开模态但 URL 正确的页面。

有人知道我需要做什么才能完成这项工作吗?

【问题讨论】:

    标签: reactjs react-redux react-router material-ui react-router-dom


    【解决方案1】:

    由于 onClick 属性调用的函数,目前您正在打开模式。当您刷新页面时,该函数不会被调用。

    这就是我要做的:

    删除&lt;Route path=":brandproduct" /&gt;并修改路由: &lt;Route path="/:productType/:category/:brandproduct?" element={&lt;ResultsList /&gt;}&gt;

    在结果列表上:

        const ResultList = () =>{    
        const { brandproduct } = useParams(); //https://reactrouter.com/web/api/Hooks/useparams
            useEffect(()=>{
            if(brandproduct){
            onToggleProductModal() 
            }
            },[brandproduct]) //every time brandproduct changes, useEffect will call this function
        // Rest of ResultList
    

    然后,您可以从 Card 组件中删除 onClick 属性,因为每次导航到 /:productType/:category/:brandproduct 时都会打开模态框,刷新页面时会包括在内

    【讨论】:

    • 谢谢!这有效,当我从path="/:productType/:category/:brandproduct?" 中删除问号时。这是有原因的还是打字错误?
    • 对不起,问号用于 react-router
    猜你喜欢
    • 1970-01-01
    • 2012-07-14
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-20
    • 2023-04-07
    相关资源
    最近更新 更多