【问题标题】:Showing Snackbar with React Redux使用 React Redux 显示 Snackbar
【发布时间】:2016-12-29 19:59:53
【问题描述】:

首先,我对 React 和 Redux 完全陌生。

每当我调度事件时,我无法将来自material-uiSnackbar 显示为通知面板。

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

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

知道如何正确实施吗?

我有一个看起来像这样的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

【问题讨论】:

    标签: reactjs redux react-redux material-ui


    【解决方案1】:

    如果我没看错,听起来您的 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;
    }
    

    【讨论】:

    • 做到了。简单而整洁。非常感谢,杰夫!
    • 但是当我需要在请求成功或失败时显示 snakbar 时我会做什么!
    猜你喜欢
    • 2020-05-16
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    相关资源
    最近更新 更多