简体   繁体   English

警告 Prop `href` 不匹配。 使用反应服务器端渲染

[英]Warning Prop `href` did not match. using react server-side-rendering

I am using react-router-dom and I am guessing that this is causing the problem, but I have no clue where to even start looking or how to fix it.我正在使用react-router-dom并且我猜这是导致问题的原因,但我不知道从哪里开始寻找或如何解决它。 I also am getting errors like Warning: Did not expect server HTML to contain a <nav> in <div> .我也收到诸如Warning: Did not expect server HTML to contain a <nav> in <div>

As I stated, I'm not really sure where to look so if you think there is certain code that would be helpful please let me know and I will post it.正如我所说,我不确定在哪里看,所以如果您认为某些代码会有所帮助,请告诉我,我会发布它。 Otherwise, I can post my code that I use to do SSR.否则,我可以发布我用来执行 SSR 的代码。

EDIT : Exact error: Warning: Prop href did not match. Server: "/profile/5a073dc44cb45b00125e5c82" Client: "profile/5a073dc44cb45b00125e5c82"编辑:确切的错误: Warning: Prop href did not match. Server: "/profile/5a073dc44cb45b00125e5c82" Client: "profile/5a073dc44cb45b00125e5c82" did not match. Server: "/profile/5a073dc44cb45b00125e5c82" Client: "profile/5a073dc44cb45b00125e5c82"

I have checked the client and it has /profile/:id so not sure where it says there is not a / , as for the other error with the <nav> in <div> , I have a nav inside my header , but I'm not really sure how to go about "fixing" that.我检查了客户端,它有/profile/:id所以不确定它在哪里说没有/ ,至于<div><nav>的另一个错误,我的标题中有一个nav ,但我我不确定如何“修复”它。

import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { renderRoutes } from 'react-router-config';
import serialize from 'serialize-javascript';
import { Helmet } from 'react-helmet';
import { matchRoutes } from 'react-router-config';

import routes from './src/routes';
import createStore from './src/stores';

function handleRender(req, res) {
  let initial = {};

  if (req.vertexSession != null && req.vertexSession.user != null) {
    initial.user = { currentUser: req.vertexSession.user };
  }
  const store = createStore.configure(initial); // create Store in order to get data from redux

  const promises = matchRoutes(routes, req.path)
    .map(({ route, match }) => {
      // Matches the route and loads data if loadData function is there
      return route.loadData
        ? route.loadData(store)
        : route.loadDataWithMatch ? route.loadDataWithMatch(store, match) : null;
    })
    .map(promise => {
      if (promise) {
        return new Promise((resolve, reject) => {
          promise.then(resolve).catch(resolve); // lets all data load even if route fails
        });
      }
    });

  Promise.all(promises).then(() => {
    const context = {};
    if (context.url) {
      return res.redirect(301, context.url); // redirect for non auth users
    }

    if (context.notFound) {
      res.status(404); // set status to 404 for unknown route
    }
    const content = renderToString(
      <Provider store={store}>
        <StaticRouter location={req.path} context={context}>
          <div>{renderRoutes(routes)}</div>
        </StaticRouter>
      </Provider>
    );
    // console.log(store.getState());
    const initialState = serialize(store.getState());

    const helmet = Helmet.renderStatic();

    res.render('index', { content, initialState, helmet });
  });
}

module.exports = handleRender;

Did you fix this already?你已经解决了吗? I had the similar problem with my react app and fixed it.我的反应应用程序遇到了类似的问题并修复了它。 Here was my problem:这是我的问题:

<Link to="./shop">Shop</Link>

my fix:我的修复:

<Link to="/shop">Shop</Link>

Whatever you are rendering with the server is the issue.无论您使用服务器渲染什么都是问题。 I suggest to comb through your routes module and see if you forgot a forward slash somewhere.我建议梳理一下您的路线模块,看看您是否在某处忘记了正斜杠。 If that doesn't work look at through the components your importing in the routes file.如果这不起作用,请查看您在路由文件中导入的组件。

To add to Kevorkian answer:要添加到Kevorkian答案:

Make sure to prefix all the routes with a /确保在所有路由前加上 /

Note the /update注意/update

<Link href={{ pathname: '/update', query: { id: product.id } }}>

This happened to me in nextjs.这在 nextjs 中发生在我身上。 It was because i had something like Link= /auth/${isLogin?"sign-up":"login"} .这是因为我有类似 Link= /auth/${isLogin?"sign-up":"login"}的东西。 This was an issue because there is no reference at compile time.这是一个问题,因为在编译时没有引用。 The should have been isLogin ? "/auth/sign-up" : "/auth/login"}应该是isLogin ? "/auth/sign-up" : "/auth/login"} isLogin ? "/auth/sign-up" : "/auth/login"}

This happened to me in a React/Next project because of next links.由于下一个链接,这发生在我的 React/Next 项目中。

This is the component这是组件

const Breadcrumb = (props) => {
  return (
    <Row>
      <Col xs="12">
        <div className="page-title-box d-sm-flex align-items-center justify-content-between">
          <h4 className="mb-0 font-size-18">{props.breadcrumbItem}</h4>
          <div className="page-title-right">
            <ol className="breadcrumb m-0">
              <BreadcrumbItem>
                <Link href="#">{props.title}</Link>
              </BreadcrumbItem>
              <BreadcrumbItem active>
                <Link href="#">{props.breadcrumbItem}</Link>
              </BreadcrumbItem>
            </ol>
          </div>
        </div>
      </Col>
    </Row>
  );
};

Here we have Link href="#" (This is the server side)这里我们有Link href="#" (这是服务器端)

<li class="breadcrumb-item">
  <a href="/search?searchTerm=a00&amp;codeSets=1%2C2%2C3%2C4%2C5%2C6%2C7#">Home
  </a>
</li>

After the page loaded, it becomes something like that above (This is the client side)页面加载后,就变成了上面的样子(这里是客户端)

So we have a mismatch here in the DOM and we get this warning所以我们在 DOM 中有一个不匹配的地方,我们收到了这个警告

SOLUTION解决方案

I was rendering this component on my pages and getting this warning.我在我的页面上渲染了这个组件并收到了这个警告。 As a solution, i have implemented dynamic content approach checking some state values before rendering the element.作为一种解决方案,我实施了动态内容方法,在渲染元素之前检查一些状态值。

For instance in my code detail page, I have done that like below.例如,在我的代码详细信息页面中,我已经完成了如下操作。

const CodeDetail = (props) => {
    const [code, setCode] = useState<any>(null);

    useEffect(() => {
        if (props.router.query.code) {
            if (codesData.filter(codeData => codeData.code == props.router.query.code).length > 0) {
                setCode(codesData.find(codeData => codeData.code == props.router.query.code));
            }
            else {
                setCode({});
            }
        }
    }, [props.router]);

    let pageContent;

    if (code !== null) {
        pageContent = (<Container fluid={true}><Breadcrumbs title="Codes" breadcrumbItem="Code Detail" /></Container>)
    }
    else {
        pageContent = null;
    }

    return(
        <React.Fragment>{pageContent}</React.Fragment>
    );
};

I just want to chip in that with Next's Link component it will accept an empty string for an href property like it does in native HTML.我只想在 Next 的Link组件中加入它,它将接受一个空字符串作为href属性,就像它在原生 HTML 中所做的那样。 If you really want a link that links to nowhere you HAVE to use # .如果您真的想要一个链接到任何地方的链接,您必须使用# That's how I got my error.这就是我得到错误的方式。

暂无
暂无

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

相关问题 Next.Js 带有样式组件的 React 应用程序。 警告:道具 `className` 不匹配。 服务器:“x” 客户端:“y” - Next.Js React app with styled components. Warning: Prop `className` did not match. Server: "x" Client: "y" nextjs:警告:道具 `className` 不匹配。 服务器:“x” 客户端:“y” - nextjs: Warning: Prop `className` did not match. Server: "x" Client: "y" 道具&#39;aria-activedescendant`不匹配。 反应-选择 - Prop `aria-activedescendant` did not match. react-select 文本内容不匹配。 React 16 中的警告 - Text content did not match. Warning in React 16 `className` 不匹配。 服务器: - `className` did not match. Server: 根据屏幕尺寸设置视频源会触发“警告:道具`src`不匹配”。 - Setting video source depending on screen size triggers "Warning: Prop `src` did not match." NextJS React 应用程序样式组件未正确呈现:警告:Prop `className` 不匹配 - NextJS React app styled component not rendering correct: Warning: Prop `className` did not match material-ui客户端警告:道具&#39;style&#39;不匹配 - material-ui client side warning: Prop `style` did not match 我可以将 UseState 与服务器端渲染一起使用吗? Nextjs/JavaScript - Can I use UseState with Server-Side-Rendering? Nextjs/JavaScript Next.js:如何将仅外部客户端的 React 组件动态导入到开发的服务器端渲染应用程序中? - Next.js: How to dynamically import external client-side only React components into Server-Side-Rendering apps developed?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM