【问题标题】:How to re-render a variable using useEffect on a new route change in react如何在 react 中的新路由更改上使用 useEffect 重新渲染变量
【发布时间】:2021-07-26 07:53:11
【问题描述】:

当路径名为“/”时,我正在尝试设置组件的宽度。

我在首页和其余页面上分别使用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>
  )
}

【问题讨论】:

    标签: reactjs react-router components router use-effect


    【解决方案1】:

    你的 useEffect 有问题,你必须听历史变化才能使钩子起作用,现在你正在听 [smWidth, lgWidth],它告诉 react,每当这两个变量发生变化时,更新组件。

    这是codepen 链接。

    这应该适合你。

    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>
      );
    });
    

    【讨论】:

    • 知道了,我知道 smWidth 和 lgWidth 不会重新渲染。
    • useEffect 告诉反应组件该组件应该重新渲染的基础。在您的代码中,变量 [smWidth, lgWidth] 根本没有改变。所以组件不会再次重新渲染。
    猜你喜欢
    • 2022-07-15
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    • 2021-12-10
    • 2021-08-13
    • 1970-01-01
    相关资源
    最近更新 更多