首页 > 解决方案 > 用 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]
}

标签: javascriptreactjsreact-transition-group

解决方案


推荐阅读