我开始使用REACT - HOOK - REDUX和REACT ROUTER创建我的第一个应用程序。目前,只有当用户转到主页时,应用程序才能正常工作,主页不使用任何反应状态(它是一个带有欢迎的静态页面)。如果用户使用其他链接,应用程序就会崩溃,因为redux状态中没有数据。我该如何处理这种情况?我想显示一个按钮来执行刷新。
让我给你看一下当前的代码:
App.js
import './styles.css';
import React, {useState, useEffect} from "react";
import "semantic-ui-css/semantic.min.css";
import { Header } from 'semantic-ui-react'
import BurgerSidebar from './components/sidebar/BurgerSidebar';
import { useDispatch, useSelector } from "react-redux";
import { requestData } from "./components/redux/actions";
import LoadingOverlay from 'react-loading-overlay';
function App() {
const dispatch = useDispatch();
const DataReducer = useSelector((state) => state.data);
const dataLoadingStatus = DataReducer.isLoading;
const [refresh, setRefresh] = useState(0);
useEffect(() => {
dispatch(requestData());
}, [refresh]);
return (
<div id="App">
<LoadingOverlay
active={dataLoadingStatus}
spinner
text='Loading your content...'
>
<div className="ui inverted segment">
<Header as='h1' textAlign='center'>
<Header.Content>
Data Dashboard
</Header.Content>
</Header>
</div>
<BurgerSidebar />
</LoadingOverlay>
</div>
);
}
export default App;
这是一个组件的例子,路由器可以从主页重定向,用户可以直接访问。Dashboard.js示例
import {React} from 'react'
import { Header, Container, Segment, Icon, Divider, Card, Grid, Statistic } from 'semantic-ui-react'
import { useSelector } from "react-redux";
const Dashboard = () => {
const DataReducer = useSelector((state) => state.data);
const customData = DataReducer.data;
const totalusers = customData.users.length;
return(
<main id="page-wrap">
<Container text>
<Header as='h2'>Dashboard</Header>
<Segment>
<Divider horizontal>
<Header as='h4'>
<Icon name='chart bar' />
Statistics
</Header>
</Divider>
<Grid columns={1} relaxed='very'>
<Grid.Column>
<Card fluid>
<Card.Content>
<Card.Header>Total Users</Card.Header>
<Statistic>
<Statistic.Value>{totalusers}</Statistic.Value>
<Statistic.Label>Users of the system</Statistic.Label>
</Statistic>
</Card.Content>
</Card>
</Grid.Column>
</Grid>
</Segment>
</Container>
</main>
);
}
export default Dashboard
所以,我们的想法是在状态。数据是空的,但不幸的是似乎不起作用。任何建议吗?
谢谢西蒙。
有两种方法可以解决这个问题。您可以在创建存储时初始化状态。https://redux.js.org/usage/structuring-reducers/initializing-state
或者你的组件应该以一种可以处理未定义或空状态变量的方式编写