我有一个从文件接收数据的组件。现在,在从服务器加载此数据时,它显示Loader。我想在更新组件时,它不是显示Loader,而是显示旧组件。如果删除加载器,则数据没有时间加载,元素显示为零。怎么做?
import React, { Component } from 'react';
import {connect} from 'react-redux'
import PropTypes from 'prop-types';
import {mapToArr} from '../helpers';
import Table from './Table';
import Loader from './Loader';
import {loadAllTables} from '../AC'
class TablesList extends Component {
static propTypes = {
tables: PropTypes.array.isRequired,
};
componentDidMount() {
const {loaded, loading, loadAllTables} = this.props;
if (!loaded || !loading) loadAllTables();
};
render() {
const { tables, loading } = this.props;
if (loading) return <Loader/>;
const tablesElements = tables.map(table =>
<Table table = {table} key = {table.id}/>
);
return (
<table>
<tbody>
{tablesElements}
</tbody>
</table>
);
};
};
export default connect((state) => {
return {
tables: mapToArr(state.tables.entities),
loading: state.tables.loading,
loaded: state.tables.loaded
}
}, {loadAllTables})(TablesList);
答案 0 :(得分:1)
您可以更改应用程序的体系结构。
让我们假设,state.tables.entities
存储了我们的数据。然后我们将state.tables.loading
更改为state.tables.status
。
我们的status
字段必须声明为字符串变量,可以是'FETCH'
,'COMPLETE'
或'DIRTY'
。
当状态为'DIRTY'
时,我们会显示Loading
组件。当状态为'FETCH'
时,我们会在组件中显示旧数据。
有一些例子:
import React, { Component } from 'react';
import {connect} from 'react-redux'
import PropTypes from 'prop-types';
import {mapToArr} from '../helpers';
import Table from './Table';
import Loader from './Loader';
import {loadAllTables} from '../AC'
class TablesList extends Component {
static propTypes = {
tables: PropTypes.array.isRequired,
status: PropTypes.oneOf(['FETCH', 'COMPLETE', 'DIRTY']
};
componentDidMount() {
const {status} = this.props;
if (status === 'DIRTY') loadAllTables();
};
render() {
const { tables, status } = this.props;
if (status === 'DIRTY') return <Loader/>;
const tablesElements = tables.map(table =>
<Table table = {table} key = {table.id}/>
);
return (
<table>
<tbody>
{tablesElements}
</tbody>
</table>
);
};
};
export default connect((state) => {
return {
tables: mapToArr(state.tables.entities),
status: state.tables.status,
}
}, {loadAllTables})(TablesList);
&#13;
现在,您的loadAllTables
动作创建者会调用多个动作:
- FETCH_TABLE_DATA
,不会更改state.tables.entities
,但会将state.tables.status
更改为FETCH
- RECEIVE_TABLE_DATA
,更改state.tables.entities
并将state.tables.status
设置为COMPLETE
。