javascript - 用 hooks api 行为不端反应烤面包机
问题描述
我正在尝试使用 React 的 hook api 构建一个烤面包机组件,但我不知道如何使它正常运行。现在所有的吐司都消失了,1 被删除,其余的出现,循环重复。
理想情况下,最旧的 Toast 通知会消失,而其余的则清晰可见。
链接到 REPL: https ://repl.it/@nikolaipaul/FabulousHideousMicrobsd
下面是 Toast 组件的代码:
const Toast = ({ id, message, remove }) => {
const [isShown, setIsShown] = React.useState(true)
React.useEffect(() => {
if (isShown) {
const timeout = setTimeout(() => {
console.log(`hiding toast id ${id}`)
setIsShown(false)
}, 2000)
return () => clearTimeout(timeout)
}
})
return (
<CSSTransition
classNames="toast"
unmountOnExit
mountOnEnter
appear
in={isShown}
timeout={300}
onExited={() => remove(id)}>
<div className="toast">{message}</div>
</CSSTransition >
)
}
以及管理 toast 列表的钩子:
export const useToast = () => {
const [toasts, setToasts] = React.useState([])
const add = message => {
const id = Math.random().toString(36).substr(2, 9)
const toast = {
id,
message,
remove,
}
console.log(`adding toast id ${id}`)
setToasts(toasts => toasts.concat(toast))
}
const remove = id => {
console.log(`removing toast id ${id}`)
setToasts(toasts => toasts.filter(toast => toast.id !== id))
}
const Toaster = () => {
const toaster =
<div style={{ position: "fixed", right: 0, top: 0 }}>
{toasts.map(toast => <Toast {...toast} key={toast.id} />)}
</div>
return ReactDOM.createPortal(toaster, document.getElementById("toasts"))
}
return [Toaster, add]
}
解决方案
推荐阅读
- unity3d - 如何删除 Unity 3d 右上角的 Gizmo 透视图标?
- mysql - MySQL自动分配外键ID
- java - 如何将 DER 编码的 OCTET 字符串用于 X509Certificate::getExtensionValue(oid) 返回的扩展值
- c++ - `std::call_once` 在 Windows 上的 Clang 12 上总是出现段错误(使用 libstdc++ 时)
- pyspark - 如何将字符串从 Databricks 推送到 Snowflake 中的时间戳
- ios - 在上传之前如何检查数据文件的大小(Flutter)
- r - R:与 R 中的 glm 和 mle2 包不同的结果
- java - firebase 云消息在服务器上不起作用
- python-3.x - 使用python获取机器登录用户名
- c - float 到 int 的隐式转换和价值损失的可能性