使用 React Redux 显示 Snackbar

Showing Snackbar with React Redux

首先,我是 React 和 Redux 的新手。

每当我发送事件时,我都无法将 material-ui 中的 Snackbar 作为通知面板显示。

请参阅我的示例的模型代码。通知根本不会以这种方式显示,因为 App 组件中的 this.props.sending 在 API 调用成功时立即设置为 false

现在,如果我跳过 SOMETHING_FULFILLED 调度,一切似乎都正常。由于我的 onRequestClose 函数,Notification 组件的 state.open 设置为 false,但是由于我的 App 组件中的 this.props.sending 仍然是设置为 true - 然后每次 App 组件重新呈现它都会显示通知。

知道如何正确实施吗?

我有一个 action 看起来像这样。

const doSomething = (data) => {
  return dispatch => {
    dispatch({
      type: 'SOMETHING_PENDING',
      payload: { data }
    })

    apiCall.then((complete) => {
      dispatch({
        type: 'SOMETHING_FULFILLED',
        payload: { data }
      })
    })
  }
}

我的 reducer 看起来像这样。

const initialState = {
  sending: false
}

const SomeReducer = (state=initialState, action) => {
  switch (action.type) {
    case 'SOMETHING_PENDING': {
      return {
        ...state,
        sending: action.payload
      }
    }

    case 'SOMETHING_FULFILLED': {
      return {
        ...state,
        sending: false
      }
    }

    default: {
      return state
    }
  }
}

export default SomeReducer

我的 App 组件已连接到商店。

import React, { Component } from 'react'
import { connect } from 'react-redux'

const storeData = (store) => {
  const data = {
    sending: store.Reducer.sending
  }

  return data
}

class App extends Component {
  render() {
    return (
      <Notification sending={this.props.sending} />
    )
  }
}

export default connect(storeData)(App)

还有我的 Notification 组件。

import React, { Component } from 'react'
import Snackbar from 'material-ui/Snackbar'

class Notification extends Component {
  constructor(props) {
    super(props)
    this.state = { open: false }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.sending) {
      this.setState({ open: true })
    } else {
      this.setState({ open: false })
    }
  }

  closeNotification = () => {
    this.setState({ open: false })
  }

  render() {
    return (
      <Snackbar
        open={this.state.open}
        message={'test'}
        autoHideDuration={4000}
        onRequestClose={this.closeNotification}
      />
    )
  }
}

export default Notification

如果我没听错的话,听起来你的 Snackbar 工作正常,但它关闭得太快了。您希望它显示,但会在 4 秒后自动关闭,即使 API 调用本身只用了 0.5 秒。那是对的吗?如果是这样,我相信您可以在 state.open 从 true 更改为 false 时跳过重新渲染组件(但在从 false 更改为 true 时仍然允许渲染):

shouldComponentUpdate(nextProps, nextState) {
  // Only re-render when snackbar is going from closed to open
  return !this.state.open && nextState.open;
}