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



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

我使用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,每当这两个变量发生变化时,更新组件。

这是代码笔链接。

这应该对你有用。

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

最新更新