Javascript React Router在单击链接时未呈现正确的页面,仅在刷新页面时有效
我正在做一个简单的登录系统,并注销一个测试博客,我试图了解更多关于React的信息。链接和重定向最初运行良好,但当我完成私有路由时,链接开始呈现未找到的页面。每次单击任何链接或重定向时,它都会呈现未找到的页面。要呈现正确的页面,我需要刷新页面或手动键入 有没有人知道这里发生了什么可以帮助我更好地理解这个问题?我试了很多东西,但都没用。我相信App.js中存在一些问题,或者AuthContext.js是一个处理身份验证部分的React上下文,但我仍然不知道它是什么 App.jsJavascript React Router在单击链接时未呈现正确的页面,仅在刷新页面时有效,javascript,reactjs,Javascript,Reactjs,我正在做一个简单的登录系统,并注销一个测试博客,我试图了解更多关于React的信息。链接和重定向最初运行良好,但当我完成私有路由时,链接开始呈现未找到的页面。每次单击任何链接或重定向时,它都会呈现未找到的页面。要呈现正确的页面,我需要刷新页面或手动键入 有没有人知道这里发生了什么可以帮助我更好地理解这个问题?我试了很多东西,但都没用。我相信App.js中存在一些问题,或者AuthContext.js是一个处理身份验证部分的React上下文,但我仍然不知道它是什么 App.js function
function App() {
function CustomRoute({ isPrivate, ...rest }) {
const { loading, authenticated } = useContext(Context);
if (loading) {
return <h1>Loading...</h1>;
}
if (isPrivate && !authenticated) {
return <Redirect to='/' />;
} else {
return <Route {...rest} />;
}
}
return (
<AuthProvider>
<Router history={history}>
<Fragment>
<Navbar />
<Switch>
<Route exact path='/' component={Login} />
<Route exact path='/register' component={Register} />
<CustomRoute isPrivate exact path='/posts' component={Posts} />
<CustomRoute
isPrivate
exact
path='/post-content'
component={PostContent}
/>
<CustomRoute isPrivate exact path='/new' component={NewPost} />
<CustomRoute isPrivate exact path='/edit' component={EditPost} />
<Route component={NotFound} />
</Switch>
</Fragment>
</Router>
</AuthProvider>
);
}
export default App;
const Context = createContext();
function AuthProvider({ children }) {
const [authenticated, setAuthenticated] = useState(false);
const [loading, setLoading] = useState(true);
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
axios.defaults.headers.Authorization = `Bearer ${JSON.parse(token)}`;
setAuthenticated(true);
}
setLoading(false);
}, []);
async function handleLogin(event, values) {
event.preventDefault();
const url = 'http://localhost:5000/auth/login';
const config = {
headers: {
'Content-Type': 'application/json',
},
};
await axios
.post(url, values, config)
.then((resp) => {
const token = resp.data.token;
localStorage.setItem('token', JSON.stringify(token));
axios.defaults.headers.Authorization = `Bearer ${token}`;
setAuthenticated(true);
history.push('/posts');
})
.catch((error) => {
if (error) {
setAuthenticated(false);
localStorage.removeItem('token');
axios.defaults.headers.Authorization = undefined;
history.push('/');
}
});
}
function handleLogout(event) {
event.preventDefault();
setAuthenticated(false);
localStorage.removeItem('token');
axios.defaults.headers.Authorization = undefined;
history.push('/');
}
return (
<Context.Provider
value={{ authenticated, handleLogin, handleLogout, loading }}>
{children}
</Context.Provider>
);
}
export { Context, AuthProvider };
函数应用程序(){
函数CustomRoute({isPrivate,…rest}){
const{loading,authenticated}=useContext(Context);
如果(装载){
返回装载。。。;
}
如果(isPrivate&&!已验证){
返回;
}否则{
返回;
}
}
返回(
);
}
导出默认应用程序;
AuthContext.js
function App() {
function CustomRoute({ isPrivate, ...rest }) {
const { loading, authenticated } = useContext(Context);
if (loading) {
return <h1>Loading...</h1>;
}
if (isPrivate && !authenticated) {
return <Redirect to='/' />;
} else {
return <Route {...rest} />;
}
}
return (
<AuthProvider>
<Router history={history}>
<Fragment>
<Navbar />
<Switch>
<Route exact path='/' component={Login} />
<Route exact path='/register' component={Register} />
<CustomRoute isPrivate exact path='/posts' component={Posts} />
<CustomRoute
isPrivate
exact
path='/post-content'
component={PostContent}
/>
<CustomRoute isPrivate exact path='/new' component={NewPost} />
<CustomRoute isPrivate exact path='/edit' component={EditPost} />
<Route component={NotFound} />
</Switch>
</Fragment>
</Router>
</AuthProvider>
);
}
export default App;
const Context = createContext();
function AuthProvider({ children }) {
const [authenticated, setAuthenticated] = useState(false);
const [loading, setLoading] = useState(true);
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
axios.defaults.headers.Authorization = `Bearer ${JSON.parse(token)}`;
setAuthenticated(true);
}
setLoading(false);
}, []);
async function handleLogin(event, values) {
event.preventDefault();
const url = 'http://localhost:5000/auth/login';
const config = {
headers: {
'Content-Type': 'application/json',
},
};
await axios
.post(url, values, config)
.then((resp) => {
const token = resp.data.token;
localStorage.setItem('token', JSON.stringify(token));
axios.defaults.headers.Authorization = `Bearer ${token}`;
setAuthenticated(true);
history.push('/posts');
})
.catch((error) => {
if (error) {
setAuthenticated(false);
localStorage.removeItem('token');
axios.defaults.headers.Authorization = undefined;
history.push('/');
}
});
}
function handleLogout(event) {
event.preventDefault();
setAuthenticated(false);
localStorage.removeItem('token');
axios.defaults.headers.Authorization = undefined;
history.push('/');
}
return (
<Context.Provider
value={{ authenticated, handleLogin, handleLogout, loading }}>
{children}
</Context.Provider>
);
}
export { Context, AuthProvider };
const Context=createContext();
函数AuthProvider({children}){
const[authenticated,setAuthenticated]=使用状态(false);
const[loading,setLoading]=useState(true);
useffect(()=>{
const token=localStorage.getItem('token');
如果(令牌){
axios.defaults.headers.Authorization=`Bearer${JSON.parse(token)}`;
setAuthenticated(true);
}
设置加载(假);
}, []);
异步函数handleLogin(事件、值){
event.preventDefault();
常量url=http://localhost:5000/auth/login';
常量配置={
标题:{
“内容类型”:“应用程序/json”,
},
};
等待axios
.post(url、值、配置)
。然后((resp)=>{
const token=resp.data.token;
setItem('token',JSON.stringify(token));
axios.defaults.headers.Authorization=`Bearer${token}`;
setAuthenticated(true);
history.push('/posts');
})
.catch((错误)=>{
如果(错误){
setAuthenticated(false);
localStorage.removietem('token');
axios.defaults.headers.Authorization=未定义;
历史推送(“/”);
}
});
}
函数handleLogout(事件){
event.preventDefault();
setAuthenticated(false);
localStorage.removietem('token');
axios.defaults.headers.Authorization=未定义;
历史推送(“/”);
}
返回(
{儿童}
);
}
导出{上下文,AuthProvider};
知道是什么引起的吗?
感谢让你收到的任何东西作为成功信号发送到
document.body.innerHTML=whateverSuccessfulReponseMeh
如果你制作一个代码沙盒(例如)并提供一个工作示例,你会很幸运地得到这类问题的答案。