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

时间:2017-12-14 20:36:30

标签: javascript reactjs ant

我在我的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呈现正确但在页面刷新时此类未添加到标题中。并且控制台日志会出现错误&#34;警告:不要指望服务器HTML包含...&#34;

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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