React 在页面刷新时无法正确呈现

React does not render correct on page refresh

我在我的 React 项目中使用 ant design 和服务器端渲染。 我的 header 根据用户身份验证状态呈现。如果用户通过身份验证,则使用 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))

在整个页面加载时(我的意思是使用 link 从主页导航到会员页面)它使用 className 正确呈现,但在页面刷新时此 class 未添加到 header。并且控制台日志给出错误 "Warning: Did not expect server HTML to contain a..."

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

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

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

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