【发布时间】:2020-12-22 00:49:38
【问题描述】:
我正在尝试根据页面 URL 更改容器的背景颜色,因此如果用户导航到 URL '/movie' 它应该将背景更改为红色,否则它应该将背景设置为绿色
这是我的 index.js
import React from 'react';
import { BrowserRouter, Switch, Route, useLocation} from 'react-router-dom';
import styled from 'styled-components';
import Movies from 'pages/Movies/Movies'
import Templates from 'pages/Movies/Templates'
;
export default () => {
const location = useLocation();
return (
<>
<BrowserRouter>
<Container style={{backgroundColor:location.pathname === '/movies' ? 'red' : 'green'}}>
<Main>
<App>
<Switch>
<Route path='/templates' component={Templates} />
<Route path='/movies' component={Movies} />
</Switch>
</App>
</Main>
</Container>
</BrowserRouter>
</>
);
}
const Container = styled.div`
min-height: 100vh;
`;
不幸的是,我收到以下错误
Uncaught TypeError: Cannot read property 'location' of undefined
at useLocation (app.js:54283)
at app.js:72792
at renderWithHooks (app.js:37714)
at mountIndeterminateComponent (app.js:40129)
at beginWork$1 (app.js:41478)
at HTMLUnknownElement.callCallback (app.js:21756)
at Object.invokeGuardedCallbackDev (app.js:21805)
at invokeGuardedCallback (app.js:21860)
at beginWork$$1 (app.js:47124)
at performUnitOfWork (app.js:46032)
我需要做什么来解决这个问题?
【问题讨论】:
-
将
const更改为let。基于此处的文档-> reactrouter.com/web/api/Hooks -
不,那也不行
-
你能发布完整的错误吗?
-
@sidthesloth 完成检查更新
标签: javascript css reactjs react-router