redux React-router-Dom使用导航重新渲染问题

cx6n0qe3  于 2023-01-21  发布在  React
关注(0)|答案(1)|浏览(257)

我正在做一个Map应用程序。这是一个完整的页面Map应用程序。在应用程序中,我通过url搜索参数将状态传递给redux。我在redux上使用状态有条件地呈现组件。
搜索参数随着Map上的每次移动而变化。例如,=〉http://localhost:8080/?map = 2d&lng = 28.751577606036108&lat = 41.117485501450204&z = 10&bearing = 10&pitch = 0
=〉Map= 28.753937232765566和纬度= 40.981906338895925和Z = 14.856764993412996和方位= -111.599999999999997和俯仰= 42.0000000000000014
应用程序中的所有其他内容都显示在侧边栏上。侧边栏有几个状态,这些状态通过动态url呈现,例如=〉侧边栏的主视图位于此url目录中。“http://localhost:8080/?map = 2d&lng = 29.038691&lat = 41.055667&z = 10&bearing = 10&pitch = 0”
侧边栏的详细状态通过此URL显示。“http://localhost:8080/detail/2?map = 2d”
我有一些卡片即将在侧边栏的主状态下被触发。我正在使用useNavigate执行单击功能。但是,我的卡片会重新呈现,因为搜索参数会随着Map的每次移动而改变。
我需要做些什么来解决这个问题谢谢
useNavigateSearch.js

import {createSearchParams, useNavigate} from "react-router-dom";

const useNavigateSearch = () =\> {
const navigate = useNavigate();
return (pathname, params) =\>
navigate({ pathname, search: `?${createSearchParams(params)}` });
> };

export default useNavigateSearch;

Card.js

import useNavigateSearch from "../../../hooks/useNavigateSearch";

const Card = ({title, img, color, route,id}) => {
    const navigate = useNavigateSearch();
    console.log('render')

    const handleClick = (route,id) => {
        navigate(`${route}/${id}`, {map: '2d'})
    }
    return (

        <div className="w-24 h-20 mt-1 flex flex-col justify-center items-center cursor-pointer"
             onClick={()=> handleClick(route,id)}>
                <div className={`w-12 h-12 ${color} rounded-full flex justify-center items-center`}>
                    <img src={img} className="w-8 h-8 brightness-0 invert"/>
                </div>
                <div className="text-sm">
                    {title}
                </div>
        </div>

    )
}
6qftjkof

6qftjkof1#

不幸的是,这就是useNavigate的设计方式,如果url改变了,每个使用useNavigate的组件都会重新呈现,在他们的github页面上有一个讨论这个问题的问题:https://github.com/remix-run/react-router/issues/7634
Ryan Florance(react-router的共同创建者)的最新建议是,如果使用6.4版本,可以创建一个导出的自定义BrowserRouter,然后导入该路由器并在其上调用.navigate,而不是使用useNavigate
此问题可以使用6.4中的新路由器解决。

import { createBrowserRouter } from "react-router-dom";
const router = createBrowserRouter([ /* ... routes ... */ ]):
export { router }
import { router } from "./router";

// call this anywhere you want in your app,
// it's outside of the react render cycle and will
// never change
router.navigate("/anywhere/you/want");

参见:www.example.comhttps://github.com/remix-run/react-router/issues/7634#issuecomment-1306650156

相关问题