【问题标题】:React does not render correct on page refreshReact 在页面刷新时无法正确呈现
【发布时间】:2019-11-27 18:16:28
【问题描述】:

我在我的 React 项目中使用 ant 设计和服务器端渲染。 我的标题根据用户身份验证状态呈现。如果用户经过身份验证,则使用 appHeader。

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Layout, BackTop, Button } from 'antd'
import LandingHeader from './_Landing/Header/LandingHeader'
import AppHeader from './Common/AppHeader'
import { withRouter } from 'react-router-dom'
import { bool, object } from 'prop-types'

const { Content, Footer } = Layout;

class AppLayout extends Component {
  constructor (props) {
    super(props)
    this.state = {}
  }

  render () {
    const { children, location } = this.props

    const isLoggedIn = this.props.isAuthenticated
    let AppHeaderConditional = null
    if (isLoggedIn && location.pathname != '/' && location.pathname != '/login' && location.pathname != '/signup') {
      AppHeaderConditional = <AppHeader />
    } else {
      AppHeaderConditional = <LandingHeader />
    }

    return (
      <div className='landing-page-wrapper' data-pathname={`${location.pathname}`}>
        {AppHeaderConditional}
        <Layout>
          <Content>
            {children}
          </Content>
        </Layout>
        <BackTop>
          <Button type='primary' shape='circle' icon='up-circle-o' size='large' />
        </BackTop>
        <Footer className='footer' style={{ textAlign: 'center' }} >
          © 2017 - 
        </Footer>
      </div>
    )
  }
}

AppLayout.propTypes = {
  isAuthenticated: bool,
  children: object,
  location: object
}

const mapStateToProps = state => {
  return {
    isAuthenticated: state.user.isAuthenticated
  }
}

export default withRouter(connect(mapStateToProps)(AppLayout))

在整个页面加载时(我的意思是从主页导航到带有链接的成员页面)它使用 className 呈现正确,但在页面刷新时该类未添加到标题中。并且控制台日志给出错误“警告:不期望服务器 HTML 包含...”

我对此控制台警告进行了研究,但没有任何帮助。我尝试了 pure:false (https://github.com/reactjs/react-redux/blob/master/docs/troubleshooting.md) 和其他一些东西,但我无法解决问题。

【问题讨论】:

  • 谁将 isAuthentified 传递给您的组件?我在代码中看不到任何类名。您能否提供更多信息。看起来服务器不知道用户是否经过身份验证
  • 在浏览器控制台元素选项卡上,标题没有类(appHeader),但在 React 选项卡标题有类“appHeader”
  • 编辑问题,添加完整代码。
  • 你检查服务器和客户端的位置了吗?

标签: javascript reactjs antd


【解决方案1】:

您必须在服务器上使用 staticRouter 在客户端上使用 browserRouter - https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/guides/server-rendering.md

【讨论】:

  • 谢谢,但是客户端已经使用 BrowserRouter,服务器使用 StaticRouter。
【解决方案2】:

我找到了解决方案。你需要的都在下面。因为页面以某种方式在客户端上第二次呈现,我不知道为什么,但这是解决方案。

componentDidMount () {
   this.setState({ mounted: true })
}

【讨论】: