首页 > 解决方案 > 使用 React Hooks + Context API 的全局状态模式在移动设备上不起作用(iOS)

问题描述

所以我在 YouTube 上遵循了这个教程。当全局状态发生变化时,组件重新渲染似乎可以在桌面(Microsoft Edge)上完美运行,但是当我在我的手机(iPhone 8,在 safari 和 Google Chrome 上测试过)上测试它时它不起作用。

这是 App.js 中的代码:

function App() {
  const contentStyle = makeStyles((theme) => ({
    container: {
      padding: '5px',
      width: '100% !important',
      height: '100% !important',
      margin: 0,
      flexGrow: 1,
    },
    chart_container: {
      width: '100%', height: '100%', position: 'relative'
    },
    paper: {
      padding: theme.spacing(2),
      textAlign: 'center',
      color: theme.palette.text.secondary,
      height: 'inherit',
    },
    alternative: {
      backgroundColor: '#ffffff'
    },
    maps: {
      minHeight: '350px',
      maxHeight: '60vh',
      width: '100%',
      height: '100%'
    }
  }));
  const classes = contentStyle()
  const { state } = useContext(Context)
  return (
    <React.Fragment>
      <Navbar title='MyApp' />
      <Grid container spacing={3} className={classes.container}>
        <Grid item xs={12}>
          <Paper elevation={5} className={classes.paper + ' ' + classes.alternative}>
            <Grid container spacing={2}>
              <Grid item xs={6}>
                <Maps className={classes.maps} elevation={5} />
              </Grid>
              <Grid item xs={6}>
                <BridgeCard name={state.bridgeName} address={state.bridgeAddress} image={state.bridgeImage} />
              </Grid>
            </Grid>
          </Paper>
        </Grid>
        <Grid item xs={12}>
          <GraphTabs />
          <Paper elevation={5} className={classes.paper + ' ' + classes.alternative}>
            <canvas style={{ width: '100%', height: '60vh' }} id="chart1" />
          </Paper>
        </Grid>
      </Grid>
    </React.Fragment>
  )
}

这是 context.js:

import { createContext } from 'react'

const Context = createContext({})

export default Context

在 index.js 中

const Index = () => {
  const theme = createMuiTheme({ palette, themeName });
  const store = useGlobalState();
  return (
    <Context.Provider value={store}>
      <React.StrictMode>
        <MuiThemeProvider theme={theme}>
          <App />
        </MuiThemeProvider>
      </React.StrictMode>
    </Context.Provider>
  )
}

在 useGlobalState.js 里面:

import { useState } from 'react';

const useGlobalState = () => {
    const [state, setState] = useState({

    })

    const actions = (action) => {
        const { type, payload } = action;
        switch (type) {
            case 'setState':
                return setState(payload)
            default:
                return state;
        }
    }
    return { state, actions }
}

export default useGlobalState;

我错过了什么还是与移动浏览器有关?我进行了调试尝试,发现全局状态更改时组件不会重新渲染。有什么建议吗?

标签: javascriptreactjs

解决方案


推荐阅读