【发布时间】:2020-12-21 16:50:24
【问题描述】:
我有一个包含几页的简单应用程序,现在我想根据页面 URL 更改背景颜色 使用反应js,
预期什么?:
当路径名是/movies我想把背景改成红色
这是我目前所拥有的
import React from 'react'
function Testing() {
const[moviesUrlBackgroundColor, setMoviesUrlBackgroundColor] = useState('green');
const getMoviesUrl = window.location.pathname;
if(getMoviesUrl == '/movies'){
setMoviesUrlBackgroundColor('red');
}else{
setMoviesUrlBackgroundColor('green');
}
return (
<div>
<Container style={{backgroundColor:moviesUrlBackgroundColor}}>
Testing
</Container>
</div>
)
}
export default Testing
const Container = styled.div`
background-color:green
`;
很遗憾,我收到了以下网址
app.js:38323 Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop.
我需要做什么才能完成这项工作?
【问题讨论】:
标签: javascript css reactjs react-router