簡體   English   中英

React 在頁面刷新時無法正確呈現

[英]React does not render correct on page refresh

我在我的 React 項目中使用螞蟻設計和服務器端渲染。 我的標題根據用戶身份驗證狀態呈現。 如果用戶經過身份驗證,則使用 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 ) 和其他一些東西,但我無法解決問題。

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

我找到了解決方案。 你需要的一切都在下面。 因為不知何故頁面在客戶端上第二次呈現,我不知道為什么,但這是解決方案。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM