簡體   English   中英

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

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

當路徑名是“/”時,我正在嘗試設置組件的寬度。

我在主頁和頁面的rest上分別使用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],它告訴反應,每當這兩個變量發生變化時,更新組件。

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

暫無
暫無

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

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