【发布时间】: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