react-router v5.1.0 无法读取 undefined 的属性“位置”,

use*_*622 17 javascript css reactjs react-router

我正在尝试根据页面 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;
    
`;
Run Code Online (Sandbox Code Playgroud)

不幸的是,我收到以下错误

  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)
Run Code Online (Sandbox Code Playgroud)

我需要做什么来解决这个问题?

Dom*_*tis 34

您需要BrowserRouter移出该组件。最好是把它移到index.js并附上<App />


Bou*_*him 6

您在useLocation路由器包装的组件外部使用,在您的情况下,根组件(内部app.js)是路由器组件的包装器

请检查这一点,当您使用该钩子App.tsxQueryReducer组件时,您会看到不同之处。