问题描述
我有一个redux存储,其中包含一个看起来像
的对象rooms: {
room01 : { timestamp: 10}
room02 : { timestamp: 10}
}
当用户单击按钮时,时间戳设置为10(通过调度)。如果有时间戳,我会倒数为0,然后在整个应用中使用react-toast
设置一个Notification。
问题是我在Notification组件上没有roomId可用,因为必须将Notification组件放置在应用程序的根目录下,否则它将被卸载并且我的Notification()逻辑不起作用。 (我可以在Notification或App中访问房间,但是它以数组形式存在,例如['room01','room02'],该数组也在redux中,但是我如何选择两个房间并访问其时间戳并运行该函数来倒计时?)。
基本上,我需要检查每个房间的redux存储区中是否有时间戳,如果有,则倒计数为0并显示带有roomId的通知。导航到其他页面时,通知/设置间隔应该可以工作。
My app component
import React from 'react';
import { Route,Switch,BrowserRouter } from 'react-router-dom';
import Home from './Home';
import 'react-toastify/dist/ReactToastify.css';
import Notification from '../features/seclusion/Notification';
const App = () => {
return (
<div>
<Notification /> // if I pass in room id like so roomId={'room02'} I cant get it to work for one room
<BrowserRouter>
<Switch>
<Route exact path="/room/:id" component={Room} />
<Route exact path="/" component={Home} />
</Switch>
</BrowserRouter>
</div>);
};
export default App;
import React,{ useState,useEffect } from 'react';
import { useSelector } from 'react-redux';
import 'react-toastify/dist/ReactToastify.css';
import { ToastContainer,toast,Slide } from 'react-toastify';
import moment from 'moment';
export default function Notification() {
const timestamp = useSelector(state => state.rooms); // need to get timestamp for room01 and room02
const [timestamp,setTimestamp] = useState(null);
const [timerId,setTimerId] = useState(null);
const notify = () => {
toast(<div>alert</div>,{
position: "top-center",});
};
useEffect(() => {
if (timestamp) {
const id = setInterval(() => {
setTimestamp((timestamp) => timestamp - 1)
},1000)
setTimerId(id);
}
return () => {
clearInterval(timerId);
};
},[timestamp]);
useEffect(() => {
if(timestamp === 0){
notify();
clearInterval(timerId);
}
},[timestamp])
return (
<ToastContainer
newestOnTop={true}
transition={Slide}
autoClose={false}
/>
);
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)