【发布时间】:2020-03-26 03:16:40
【问题描述】:
我正在使用上下文 API,在我的 AuthContextProvider 中我有一个函数,我调用它然后更改路由;问题是它更改了路由但不渲染组件,我不知道为什么。我相信如果我将 auth-context.js 类转换为基于类的类,它会起作用。
我尝试返回 Redirect to ="/ /> 但这不起作用。
我很难过。如果有人可以帮忙,我会很高兴
auth-context.js
import React, { useState } from 'react';
import { withRouter, Redirect } from 'react-router-dom';
import axios from 'axios';
export const AuthContext = React.createContext({
isAuth: false,
login: () => {},
seedFirebase: () => {}
});
const AuthContextProvider = props => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
console.log(props);
const loginHandler = () => {
setIsAuthenticated(true);
props.history.push('/'); //this changes the route but does not render the component
};
//THIS FUNCTION SEEDS THE FIREBASE DATABASE
const seedDb = () => {
const data = {
items: 'Folders'
};
// axios.post('/items.json', data).then(resp => console.log(resp.data));
};
return (
<AuthContext.Provider
value={{
login: loginHandler,
isAuth: isAuthenticated,
seedFirebase: seedDb
}}
>
{props.children}
</AuthContext.Provider>
);
};
export default withRouter(AuthContextProvider);
【问题讨论】:
标签: reactjs react-router react-context