保护路线

时间:2020-09-21 10:08:05

标签: javascript reactjs

我正在尝试对我的应用程序实施路由保护,但是在连接组件时遇到问题。我在其他文件中有组件,并在App.js中将它们全部调用

App.js

function App() {
    const [auth, setAuth] = useState(false);

    return (
        <BrowserRouter>
            <div>
                <Switch>
                    <Route path='/' exact component={Login} />
                    <PrivateRoute exact path={'/dashboard'} component={Dashboard} auth={auth} />
                </Switch>
            </div>
        </BrowserRouter>
    );
}

const PrivateRoute = ({ auth, component: Component, ...rest }) => {
    return (
        <Route {...rest} render={(props) => (auth ? <Component {...props} /> : <Redirect to={{ pathname: '/' }} />)} />
    );
};

export default App;

login.js

const handleClick = () => {
    getData();
    clear();
};

const getData = async () => {
    try {
        const a = await fetch(url, { method: 'GET', headers: headers });
        const response = await a.json();
        setData(response);
        history.push({
            pathname: `/dashboard`,
        });
        return (
            <div>
            ...
                <Button variant='contained' color='primary' onClick={handleClick}>
                    Login
                </Button>
            </div>
        );
    }
    ...
};

当单击login.js中的登录按钮时,如何在App.js中将auth状态更改为true?

0 个答案:

没有答案