首先,我完全不熟悉React和Redux。顯示Snackbar與React Redux
無論何時我發送一個事件,我都會在顯示Snackbar
從material-ui
作爲通知面板時遇到麻煩。
請參閱我的示例的模型代碼。通知未完全顯示,因爲當API調用成功時,this.props.sending
在App
組件設置爲false
。
現在,如果我跳過SOMETHING_FULFILLED
調度一切似乎工作正常。在Notification
組件的state.open
設置爲false
感謝我onRequestClose
功能,但因爲在我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
這做到了。簡單而整潔。謝謝,傑夫! – wannabefounder
真棒,很高興幫助! –
但是當我需要根據請求成功或失敗時顯示snakbar時,我會做什麼! –