简体   繁体   English

我如何使用带有中继的 React 路由器?

[英]How do I use react router with relay?

I am struggling with react-router and relay integration.我正在努力解决 react-router 和中继集成问题。

As of now, I stick to this example截至目前,我坚持这个例子

It uses the useLazyLoadQuery hook, and although everything seems to work just fine, I also see another way of doing this: usePreloadedQuery .它使用useLazyLoadQuery挂钩,虽然一切似乎都运行良好,但我还看到了另一种方法: usePreloadedQuery

The docs say that the useLazyLoadQuery hook文档说useLazyLoadQuery挂钩

can trigger multiple nested or waterfalling round trips if used without caution and waits until render to start a data fetch (when it can usually start a lot sooner than render), thereby degrading performance.如果不小心使用,可能会触发多个嵌套或瀑布式往返,并等到渲染开始数据获取(这通常比渲染开始得早得多),从而降低性能。 Instead, prefer usePreloadedQuery.相反,更喜欢 usePreloadedQuery。

However, it is not clear how to integrate this with react-router and obviously, I do not want to reinvent my own router...但是,目前尚不清楚如何将其与 react-router 集成,显然,我不想重新发明自己的路由器...

Another thing I noticed is that usePreloadedQuery should be used in conjunction with useQueryLoader ;我注意到的另一件事是usePreloadedQuery应该与useQueryLoader一起使用; At the same time in docs they load it directly by just calling loadQuery() ;同时在文档中,他们通过调用loadQuery()直接加载它;

So I am not sure which way is preferred.所以我不确定哪种方式是首选。

I ended up with a wrapper like this:我最终得到了这样的包装器:

const WrappedHomePage = () => {
  const [queryRef, loadQuery] = useQueryLoader(HomePageQuery);

  // does calling it like this make any sense at all?
  useMemo(() => {
    loadQuery();
  }, [loadQuery]);

  return <HomePage queryRef={queryRef} />;
};

const HomePage = ({ queryRef }) => {
  const query = usePreloadedQuery(
    graphql`
      query HomePageQuery {
        ...HomePageContainer_repository
      }
    `,
    queryRef
  );

  return (
    <div>
      <HomePageContainer fragmentRef={query} />
    </div>
  );
};

According to the Relay docs :根据中继文档

The component-based approach of React Router v4 does not readily allow for aggregating the data requirements for nested routes, and as such does not readily permit an approach that will avoid request waterfalls from nesting QueryRenderer components. React Router v4 基于组件的方法不允许聚合嵌套路由的数据需求,因此不允许采用一种方法来避免来自嵌套 QueryRenderer 组件的请求瀑布。

So basically using react-router with Relay is out:(所以基本上将 react-router 与 Relay 一起使用是不可行的:(

Relay recommends using Found as an alternative router, which is similar to react-router. Found integrates well with Relay using the found-relay package. Relay 建议使用Found作为替代路由器,类似于 react-router。Found 使用found-relay package 与 Relay 很好地集成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM