TypeError:尝试使用带有反应路由器的上下文 api 传递数据时无法读取未定义的属性(读取“userData”)

问题描述 投票:0回答:2

我正在尝试通过上下文 api 将 UserData 从 App 组件传递到仪表板组件。但是当它重定向到 /dashboard 时,它给了我错误 TypeError: Cannot read properties of undefined (reading 'userData').我一直试图解决这个问题,但我一直没有成功。任何人都可以帮助我吗? 这是我的 app.js

function App() {
  // const [pageData, setPageData] = useState({});
  const [userData , setUserData] = useState({});
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const handleLogin = (res) => {
    // update the state of the App component with the received data
    console.log(res);
    setUserData(res);
    // you can do whatever you want with the received data here
  };




  return (
    <div className="App">
  <UserContext.Provider value={{ isLoggedIn, setIsLoggedIn, userData, setUserData}}>
    <Routes>
      <Route exact path="/dashboard" element={<Dashboard />} />
      <Route
        path="/"
        element={
          isLoggedIn ? (
            <Navigate to="/dashboard" />
          ) : (
            <Login setLoggedIn={setIsLoggedIn} handleLogin={handleLogin} />
          )
        }
      />
    </Routes>
  </UserContext.Provider>
</div>
  );
}

export default App;

这是我的仪表板组件:

const Dashboard = () => {
  const {userData} = useContext(UserContext);

  const page = ["Home", "Logout"];
  const [sidebar, setSidebar] = useState(false);
  const isMobile = useMediaQuery("(max-width:600px)"); // check if screen size is below 600px
  console.log(userData.username , userData.password);

  const handleToggle = () => {
    setSidebar(!sidebar);
  };

  return (
    <div>
      
      <Navbar pages={page} />
      <Grid container spacing={2}>
        <Grid item xs={12} sm={3}>
          {isMobile && (
            <Button style={{ margin: "8px" }} onClick={handleToggle}>
              Toggle Sidebar
            </Button>
          )}
          {!isMobile && <Sidebar />}
          {sidebar && isMobile && <Sidebar />}
        </Grid>
        <Grid item xs={12} sm={9}>
          <Grid container spacing={4}>
            <Grid item xs={12} sm={12}>
              <Typography variant="h5">Dashboard</Typography>
            </Grid>
            <Grid item xs={12} sm={12} >
              <Typography variant="h3">Welcome back! {userData.username}</Typography>
            </Grid>
            <Grid item xs={12} sm={12}>
              <Paper elevation={3} sx={{height:"15rem",width:"35rem"}}>
                <Typography variant="h6" >
                  Your Current Business Ventures
                </Typography>
                <Typography variant="body1">
                  None
                </Typography>
                <Typography variant="body1" >
                  {userData.username}
                </Typography>
              </Paper>
            </Grid>
          </Grid>
        </Grid>
      </Grid>
    </div>
  );
};

export default Dashboard;

我尝试了一些在线解决方案,但没有任何用处

reactjs react-context
2个回答
0
投票

如果您使用

React.createContext()
创建上下文,那么
context
的初始状态是
undefined
,这意味着
userData
暂时未定义。

在您的示例中,要查看

userData
,只需在
undefined
时忽略它最初在未定义对象的任何属性之前使用
?

console.log({ username: userData?.username, password: userData?.password });


0
投票

欢迎来到 Stack Overflow :)

我们看不到

res
的形状被传递给
setUserData
。现在它看起来只是一个你永远不会通过的参数。
console.log(res);
handleLogin
里面给你什么?是
undefined
吗?那就是你的答案。

你在这里调用

handleLogin
没有传递任何东西。所以
res
看起来是未定义的。

<Login setLoggedIn={setIsLoggedIn} handleLogin={handleLogin} />

您提供的很多代码似乎与您的问题无关。您是否可以提供简化版本,使我们能够更轻松地重现您的特定问题?

请在此处查看帮助他人重现问题部分:https://stackoverflow.com/help/how-to-ask:)

© www.soinside.com 2019 - 2024. All rights reserved.