请帮助我,我的代码完全搞砸了,我收到了这个错误,我无法解决它。
我知道这个问题有几个答案,但它们并没有解决我的问题。我是新手,无法找到正确的代码。
19 | useEffect(() => {
20 | const user =
JSON.parse(localStorage.getItem("user"));
21 | if (user) {
> 22 | dispatch({type:"USER",payload:user})
^ 23 | } else {
24 | history.push("/signin");
25 | }
App.js
import React, { useEffect, createContext, useReducer, useContext } from "react";
import Navbar from "./components/Navbar";
import "./App.css";
import { BrowserRouter, Route, Switch, useHistory } from "react-router-dom";
import Home from "./components/screens/Home";
import Signin from "./components/screens/Signin";
import Signup from "./components/screens/Signup";
import Profile from "./components/screens/Profile";
import CreatePost from "./components/screens/CreatePost";
import UserProfile from "./components/screens/UserProfile";
// import Hero from "./components/screens/Hero";
import { reducer, initialState } from "./reducers/userReducer";
export const UserContext = createContext();
const Routing = () => {
const history = useHistory();
const { state, dispatch } = useContext(UserContext);
useEffect(() => {
const user = JSON.parse(localStorage.getItem("user"));
if (user) {
dispatch({type:"USER",payload:user})
} else {
history.push("/signin");
}
}, []);
return (
<Switch>
<Route exact path="/">
<Home />
</Route>
{/* <Route exact path="/post">
<Hero />
</Route> */}
<Route path="/signin">
<Signin />
</Route>
<Route path="/signup">
<Signup />
</Route>
<Route exact path="/profile">
<Profile />
</Route>
<Route path="/create">
<CreatePost />
</Route>
<Route path="/profile/:userid">
<UserProfile />
</Route>
</Switch>
);
};
function App() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<UserContext.Provider value={(state, dispatch)}>
<BrowserRouter>
<Navbar />
<Routing />
</BrowserRouter>
</UserContext.Provider>
);
}
export default App;
userReducer.js
export const initialState = null;
export const reducer = (state, action) => {
if (action.type === "USER") {
return action.payload;
}
if (action.type === "CLEAR") {
return null;
}
if (action.type === "UPDATE") {
return {
...state,
followers: action.payload.followers,
following: action.payload.following,
};
}
return state;
};