React-Redux组件未在商店中显示新道具

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

我正在尝试使用react创建自己的警报组件(在这种情况下,也是Bootstrap v4)。 基本上,如果发生了某些事情需要通知用户,请创建一条消息,然后将其放入存储中,并做出反应来生成警报。 我知道我正在做的事情应该是可能的,但是我很新来做出反应,以至于我缺少/不了解反应如何工作,这导致没有警报显示。

首先,我提醒所有其他组件都可以使用,因此将其放在app.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import AppRouter from './routers/AppRouter';
import configureStore from './store/configureStore';

import Alerts from './components/controls/Alerts';

const { store, persistor } = configureStore();

const jsx = (
    <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
            <Alerts />
            <AppRouter />
        </PersistGate>
    </Provider>
);

ReactDOM.render(jsx, document.getElementById('root'));

接下来是Alerts的组件。 首先的动作:

// DISPLAY_ALERT
export const displayAlert = (message, severity) => ({
    type: 'DISPLAY_ALERT',
    message: message,
    severity: severity
});

// DISMISS_ALERT
export const dismissAlert = (id) => ({
    type: 'DISMISS_ALERT',
    id: id
});

减速器:

const alertsDefaultState = [];

const alertNotify = (state, action) => {
    let queue = state;

    if (!queue || !Array.isArray(queue))
        queue = [];

    let newAlert = {
        id: getUniqueId(),
        message: action.message,
        severity: action.severity
    };

    queue.push(newAlert);

    return queue;
};

const alertDismiss = (state, action) => {
    const newQueue = state.filter((element) => element.id !== action.id);

    return newQueue;
};

const getUniqueId = () => {
    return (Date.now().toString(36) + Math.random().toString(36).substr(2, 5)).toUpperCase();
};

export default (state = alertsDefaultState, action) => {
    switch (action.type) {
        case 'DISPLAY_ALERT':
            return alertNotify(state, action);
        case 'DISMISS_ALERT':
            return alertDismiss(state, action);
        case 'LOG_OUT_OF_API':
            return [];
        default:
            return state;
    }
};

商店:

import { createStore, combineReducers } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import alertsReducer from '../reducers/alerts';

export default () => {
    const persistConfig = {
        key: 'root',
        storage,
    };

    let reducers = combineReducers({
        // Other reducers
        alerts: alertsReducer
    });

    let store = createStore(
        persistReducer(persistConfig, reducers),
        window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
    );

    let persistor = persistStore(store);

    return { store, persistor };
};

最后是Alerts组件:

import React from 'react';
import { connect } from 'react-redux';
import { dismissAlert } from '../../actions/alerts';

class Alerts extends React.Component {
    constructor(props) {
        super(props);
    }

    getAlerts = () => {
        if (!this.props.alerts || this.props.alerts.length === 0)
            return null;

        const alertFixed = {
            position:'fixed',
            top: '0px',
            left: '0px',
            width: '100%',
            zIndex: 9999,
            borderRadius: '0px'
        };

        return (
            <div style={alertFixed}>
                {
                    this.props.alerts.map((alert) => {
                        const alertClass = `alert alert-${alert.severity} alert-dismissible m-4`
                        setTimeout(() => {
                            this.props.dispatch(dismissAlert(alert.id));
                        }, 5000);
                        return (
                            <div key={alert.id} id={alert.id} className={alertClass} role="alert">
                                <button type="button" className="close" data-dismiss="alert" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                                { alert.message }
                            </div>
                            );
                        }
                    )
                }
            </div>
        );
    }

    render() {
        return this.getAlerts()
    }
}

const mapStateToProps = (state) => {
    return {
        alerts: state.alerts
    }
};

export default connect(mapStateToProps)(Alerts);

最后一件事,我有一个const类型的警报类型:

export default {
    Info: 'info',
    Success: 'success',
    Warning: 'warning',
    Error: 'danger',
};

如果我运行上面的代码并在alerts store中添加了某些内容,那么它将被呈现。 但是,如果我在事件中添加了一些东西(例如单击按钮),则可以看到警报已添加到商店中,但是组件不会将警报添加到DOM中。

我想念什么?

编辑:

这是一个代码沙箱

reactjs redux lifecycle
1个回答
1
投票

数组是Javascript中的引用类型

在你的

const alertNotify = (state, action) => {
    let queue = state;

    if (!queue || !Array.isArray(queue))
        queue = [];

    let newAlert = {
        id: getUniqueId(),
        message: action.message,
        severity: action.severity
    };

    queue.push(newAlert);

    return queue;
};

而不是做这样的事情

 let queue = state;

您需要制作一个副本 (而不是引用它),然后执行

queue.push(newAlert);

即将您的初始队列声明更改为此(我正在使用传播运算符复制通过状态的副本,然后在队列中推送newAlert

let queue = [...state];

由于您的队列返回时,其中没有状态

此条件已被解雇

 if (!this.props.alerts || this.props.alerts.length === 0)
© www.soinside.com 2019 - 2024. All rights reserved.