如何在 React 中的新路由更改上使用 useEffect 重新渲染变量

How to re-render a variable using useEffect on a new route change in react

我试图在路径名为“/”时设置组件的宽度。

我已经使用 useEffect 分别将主页和其余页面的宽度设置为 800px 和 1200px。

但是,当我使用 useEffect 并单击按钮更改路线时,useEffect 似乎没有重新呈现宽度变量。

目前,在初始页面加载时,宽度样式会根据我所在的路线而变化,但当我切换路线时,宽度尺寸不会发生变化。

简而言之,如何根据当前显示的路线更改宽度变量?

这是我目前的情况:

function Window() {
  const [width, setWidth] = useState(null)
  let smWidth = '800px'
  let lgWidth = '1200px'

  useEffect(() => {
    let pathname = window.location.pathname
    if (pathname === '/') {
      console.log(pathname)
      setWidth(smWidth)
    } else {
      console.log(pathname)
      setWidth(lgWidth)
    }
  }, [smWidth, lgWidth])

  return (
    <WindowWrapper style={{ width }}>
     </Switch>
       <Route path="/goals" component={goals} />
      <Route path="/" component={Home} />
    </Switch>
  )
}

你的 useEffect 有问题,你必须监听历史变化才能使挂钩工作,现在你正在监听 [smWidth, lgWidth],它告诉 React,只要这两个变量发生变化,就更新组件。

这里是codepenlink.

这应该适合你。

import React, { useEffect, useState } from 'react';
import { withRouter, Switch, Route, Link } from 'react-router-dom';
import Home from './Home';
import Contactus from './Contactus';

export default withRouter(function App({ location }) {
  const [currentPath, setCurrentPath] = useState(location.pathname);
  const [width, setWidth] = useState();
  let smWidth = '100px';
  let lgWidth = '200px';

  useEffect(() => {
    const { pathname } = location;
    setCurrentPath(pathname);

    if (pathname === '/') {
      console.log(pathname);
      setWidth(smWidth);
    } else {
      console.log(pathname);
      setWidth(lgWidth);
    }
  }, [location.pathname]);

  return (
    <div className="App">
      <div className="p-1">
        <Link to="/" className="btn btn-primary">
          Home
        </Link>
        {' - '}
        <Link to="/contactus" className="btn btn-primary">
          Contact us
        </Link>
      </div>
      <div className="p-1">
        <div style={{ width }} className="alert alert-info mt-1" role="alert">
          Demo Width Change: {width}
        </div>
      </div>
      <Switch>
        <Route path="/" exact component={Home} />
        <Route path="/contactus" component={Contactus} />
      </Switch>
    </div>
  );
});