用React Redux显示Snackbar

wan*_*der 5 reactjs redux material-ui react-redux

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

每当我调度事件时,在将Snackbarfrom material-ui作为通知面板显示时都会遇到麻烦。

请参见我的示例的样机代码。该通知不,因为这一切的方式显示this.props.sendingApp组件集来false时,立即API调用是成功的。

现在,如果我跳过SOMETHING_FULFILLED调度,一切似乎都可以正常工作。在state.open该的Notification组件设置为false感谢我的onRequestClose功能,但由于this.props.sending我的App部件仍设置true-然后每次App组件重新呈现它显示的通知。

知道我将如何正确实施吗?

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

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

    apiCall.then((complete) => {
      dispatch({
        type: 'SOMETHING_FULFILLED',
        payload: { data }
      })
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

我的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)
Run Code Online (Sandbox Code Playgroud)

和我的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
Run Code Online (Sandbox Code Playgroud)

Jef*_*oud 3

如果我没理解错的话,听起来您的 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;
}
Run Code Online (Sandbox Code Playgroud)