React.js组件在刷新时缺少样式

时间:2018-12-13 10:55:34

标签: javascript reactjs material-ui

我正在使用带有React-Router和Material ui的React。第一次加载时,所有内容看起来都是正确的,但是当我刷新页面时,所有样式都会丢失。

如果我更改了代码并重新编译,则样式会正确重新加载

刷新时:1 初始加载时:2

这是服务器端渲染

const generateClassName = createGenerateClassName()
   const context = {}
   const markup = ReactDOMServer.renderToString(
      <StaticRouter location={req.url} context={context}>
         <JssProvider registry={sheetsRegistry} generateClassName={generateClassName}>
            <MuiThemeProvider theme={theme} sheetsManager={new Map()}>
              <MainRouter/>
            </MuiThemeProvider>
         </JssProvider>
      </StaticRouter>
     )
    if (context.url) {
      return res.redirect(303, context.url)
    }
    const css = sheetsRegistry.toString()
    res.status(200).send(Template({
      markup: markup,
      css: css
    }))
})

模板:

export default ({markup, css}) => {
    return `<!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8">
          <title>Budget App</title>
          <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,300,400">
          <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
          <style>
              a{
                text-decoration: none
              }
          </style>
        </head>
        <body style="margin:0">
          <div id="root">${markup}</div>
          <style id="jss-server-side">${css}</style>
          <script type="text/javascript" src="/dist/bundle.js"></script>
        </body>
      </html>`
}

和页面:

import React, {Component} from 'react'
import PropTypes from 'prop-types'
import { withStyles } from '@material-ui/core'
import {list} from './api-cat.js'
import auth from '../auth/auth-helper'
import AddCat from './AddCat'
import Category from './Category.js'
import Paper from '@material-ui/core/Paper'
import Typography from '@material-ui/core/Typography'
import Grid from '@material-ui/core/Grid'
import Divider from '@material-ui/core/Divider'
import { Chart } from "react-google-charts"

const pieOptions = {
  title: "",
  legend: {
    position: "bottom",
    alignment: "center",
  },
  tooltip: {
    showColorCode: true
  },
  chartArea: {
    left: 0,
    top: 50,
    width: "100%",
    height: "80%"
  },
  fontName: "Roboto"
}

const styles = theme => ({
  root: theme.mixins.gutters({
    maxWidth: 600,
    margin: 'auto',
    padding: theme.spacing.unit * 3,
    marginTop: theme.spacing.unit * 5
  }),
  title: {
    margin: `${theme.spacing.unit * 3}px 0 ${theme.spacing.unit * 2}px`,
    color: theme.palette.protectedTitle
  }
})

class ListCat extends Component {
  state = {
    cats: [],
    chartImageURI: "",
  }

  componentDidMount() {
    this.initCats()
  }

  initCats = () => {
    const jwt = auth.isAuthenticated()
    list({t: jwt.token}).then((data) => {
      if (data.error) {
        console.log(data.error)
      } else {
        this.setState({cats: data})
      }
    })

  }

  handleChange = () => {
    this.initCats()
  }

  render() {
    const {classes} = this.props
    const {cats} = this.state
    const catGraph = cats.map((cat) => {
      return [cat.name, cat.budget]

    })
    catGraph.unshift(["Name", "Budget"])
    const budget = this.state.cats.map((data)=> {
      return (data.budget)
    }).reduce(( accumulator, currentValue ) => accumulator + currentValue, 0)
    return(
      <Paper className={classes.root} elevation={4}>
        <Typography type='title' className={classes.title}>
          All Categories
        </Typography>
        <AddCat onClick={this.handleChange}/>
        <Grid container spacing={24}>
        {cats.map((cat, i) => {
          return (
            <Category key={i} category={cat} onClick={this.handleChange}/>
          )
        })}
        </Grid>
        <Paper className={classes.root}>
          <Typography type='title' className={classes.title}>
            Spending chart (${budget} per month)
          </Typography>

          <Chart
            chartType="PieChart"
            data={catGraph}
            options={pieOptions}
            graph_id="PieChart"
            width={"100%"}
            height={"400px"}
            legend_toggle
          />
        </Paper>
      </Paper>
    )
  }
}

ListCat.PropTypes = {
  classes: PropTypes.object.isRequired
}

export default withStyles(styles)(ListCat)

0 个答案:

没有答案