通常,(不是使用 Redux)它会在任何父组件中处理,该组件将 webSocketMessage 作为 prop 传递给该组件。假设您将消息作为状态存储在父级中,它可能类似于...
import React, {useEffect, useState} from 'react';
const ParentComponent = () => {
const [webSocketMessage, setWebSocketMessage] = useState()
useEffect(() => {
if (webSocketMessage){
setTimeout(() => setWebsocketMessage(null), 30000)
}
}, [webSocketMessage])
return <ChildComponent webSocketMessage={webSocketMessage} />
}
export default ParentComponent;
同样的想法可以转化为清除消息的 redux 操作,因为您正在使用 redux 存储来保存该消息。基本思想是负责发送该道具的任何人(在您的情况下为 Redux)也需要负责清除它,因此您最终得到...
const clearMessage = () => dispatch({type: 'CLEAR_MESSAGE'})
dispatch({type: 'CLEAR_MESSAGE'}) 然后可以在你的 reducer 中用于将状态中的消息设置为 null、一个空数组或任何你需要的东西。
您的消息缩减器可能如下所示:
export function messageReducer(state = [], action) {
switch(action.type){
case 'ADD_MESSAGE':
return [...state, action.errorMessage]
case 'CLEAR_MESSAGES':
return []
default:
return state
}
}
只要你的根 reducer 已经使用了某种消息 reducer,你就应该能够将这种情况添加到 switch 语句中。
最后,在这个 sn-p 取自的组件中,你可以有类似...
useEffect(() => {
setTimeout(props.clearMessages, 30000)
}
最终
const Whatever = () => {
// code
useEffect(() => {
setTimeout(props.clearMessages, 30000)
}
//other code
}
const mapStateToProps = (state) => {
return {
webSocketMessage: state.webSocketMessage
}
}
const mapDispatchToProps = (dispatch) => {
return {
clearMessages: () => dispatch({type: 'CLEAR_MESSAGES'})
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Whatever);