Reactjs 如何在react中的新路由更改上使用useEffect重新呈现变量

Reactjs 如何在react中的新路由更改上使用useEffect重新呈现变量,reactjs,react-router,components,router,use-effect,Reactjs,React Router,Components,Router,Use Effect,我试图在路径名为“/”时设置组件的宽度 我已经使用useEffect将主页和其他页面的宽度分别设置为800px和1200px 但是,当我使用useEffect并单击一个按钮来更改路由时,useEffect似乎不会重新启用宽度变量 目前,在初始页面加载时,宽度样式确实会根据我所在的路由而改变,但当我切换路由时,宽度大小不会发生变化 简而言之,如何根据当前显示的路线更改宽度变量 以下是我到目前为止的情况: 函数窗口(){ 常量[width,setWidth]=useState(null) 设smWi

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

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

但是,当我使用useEffect并单击一个按钮来更改路由时,useEffect似乎不会重新启用宽度变量

目前,在初始页面加载时,宽度样式确实会根据我所在的路由而改变,但当我切换路由时,宽度大小不会发生变化

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

以下是我到目前为止的情况:

函数窗口(){
常量[width,setWidth]=useState(null)
设smWidth='800px'
设lgWidth='1200px'
useffect(()=>{
让pathname=window.location.pathname
如果(路径名=='/')){
console.log(路径名)
设置宽度(smWidth)
}否则{
console.log(路径名)
设置宽度(lgWidth)
}
},[smWidth,lgWidth])
返回(
)
}

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

这里是链接

这应该对你有用

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>
  );
});
import React,{useffect,useState}来自“React”;
从“react router dom”导入{withRouter,Switch,Route,Link};
从“./主页”导入主页;
从“/Contactus”导入Contactus;
使用路由器导出默认值(函数App({location}){
const[currentPath,setCurrentPath]=useState(location.pathname);
const[width,setWidth]=useState();
设smWidth='100px';
设lgWidth='200px';
useffect(()=>{
const{pathname}=位置;
setCurrentPath(路径名);
如果(路径名=='/')){
console.log(路径名);
设置宽度(smWidth);
}否则{
console.log(路径名);
设置宽度(lgWidth);
}
},[location.pathname]);
返回(
家
{' - '}
联系我们
演示宽度更改:{Width}
);
});

明白了,我想smWidth和lgWidth不会重新渲染。useEffect会告诉react组件该在哪个基础上重新渲染组件。在您的代码中,变量[smWidth,lgWidth]根本没有更改。因此该组件不会再次重新招标。