首先,我对 React 和 Redux 完全陌生。
我在显示 Snackbar
时遇到问题来自material-ui
每当我发送事件时作为通知面板。
请参阅我的示例的模型代码。自this.props.sending
以来,通知根本没有以这种方式显示。在App
组件设置为false
API调用成功后立即执行。
现在,如果我跳过 SOMETHING_FULFILLED
dispatch 一切似乎工作正常。 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 }
})
})
}
}
还有我的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;
}
关于reactjs - 使用 React Redux 显示 Snackbar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41386427/