gpt4 book ai didi

javascript - react-router v5.1.0无法读取未定义的属性 'location',

转载 作者:行者123 更新时间:2023-12-03 07:02:36 27 4
gpt4 key购买 nike

我正在尝试根据页面 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)
我需要做什么来解决这个问题?

最佳答案

你需要搬家BrowserRouter出那个组件。最好是移到index.js并附上 <App />

关于javascript - react-router v5.1.0无法读取未定义的属性 'location',,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63712504/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com