如何显示旧组件

时间:2018-02-17 12:35:09

标签: javascript reactjs redux react-redux

我有一个从文件接收数据的组件。现在,在从服务器加载此数据时,它显示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);

1 个答案:

答案 0 :(得分:1)

您可以更改应用程序的体系结构。

让我们假设,state.tables.entities存储了我们的数据。然后我们将state.tables.loading更改为state.tables.status

我们的status字段必须声明为字符串变量,可以是'FETCH''COMPLETE''DIRTY'

当状态为'DIRTY'时,我们会显示Loading组件。当状态为'FETCH'时,我们会在组件中显示旧数据。

有一些例子:

&#13;
&#13;
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;
&#13;
&#13;

现在,您的loadAllTables动作创建者会调用多个动作: - FETCH_TABLE_DATA,不会更改state.tables.entities,但会将state.tables.status更改为FETCH - RECEIVE_TABLE_DATA,更改state.tables.entities并将state.tables.status设置为COMPLETE