Dispatch a Redux action with the subsequent action as payload to show a snackbar or dialog of Material UI

前端 未结 1 1052
北荒
北荒 2021-02-19 19:25

I\'m using React with Redux and Material UI to build a webapp. The webapp is made of several pages and components. I know that a snackbar or dialog should be directly connected

1条回答
  •  误落风尘
    2021-02-19 20:15

    Actually, right now usign redux was changed a little bit. We use createAction from redux-act, properly we use createReducer further. In a component we use connect decorator or class from react-redux. Connector provides redux state, dispatched actions, parent props. So for our snackbar we have:

    1. actions:

      export const showMessageTop = createAction();
      export const closeMessageTop = createAction();
      
    2. Reducer:

      import {createReducer} from 'redux-act';
      import * as ac from '../actionCreators/messageTop';
      export default createReducer(
        {
          [ac.showMessageTop]: (state, messageText) => ({messageText}),
          [ac.closeMessageTop]: () => ({messageText: ''}),
        },
        {
          messageText: window.location.search === '?login=1'
                     ? 'Welcome'
                     : '',
        }
      )
      
    3. And a component(use decorator instead of class):

      import {closeMessageTop} from '../../actionCreators/messageTop'; 
      import MessageTop from './MessageTop';
      @connect(state => ({
        // gettext: gettext(state.locale.messages),
        messageText: state.messageTop.messageText,
      }))
      export default class MessageTopContainer extends React.Component {
      ...
      

    So in current props we have this.props.messageText. And we can show this bar if we have message, or we can invoke closeAction which sets up messageText in empty string.

    0 讨论(0)
提交回复
热议问题