制作包含调度的导出功能

发布于 2025-02-01 21:18:32 字数 460 浏览 1 评论 0原文

我想发挥我可以导出并在项目周围使用它的功能。 问题是我需要使用调度。

import React from 'react'
import { useDispatch } from "react-redux";
import { displayMessage } from '../App/store/mixed'

const dispatch = useDispatch()

export const test = () => {


    dispatch(displayMessage({ show: true, text: `test` }));
    setTimeout(() => {
        dispatch(displayMessage({ show: false, text: '' }))
    }, 2000);
}

上面的代码将使您了解我要完成的工作。

这样的事情甚至可行吗?

I want to make function that I can export it and use it around the project.
The problem is that i need to use dispatch.

import React from 'react'
import { useDispatch } from "react-redux";
import { displayMessage } from '../App/store/mixed'

const dispatch = useDispatch()

export const test = () => {


    dispatch(displayMessage({ show: true, text: `test` }));
    setTimeout(() => {
        dispatch(displayMessage({ show: false, text: '' }))
    }, 2000);
}

The code above will give you idea what i am trying to accomplish.

Is something like this even doable?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情丝乱 2025-02-08 21:18:32

您可以制作一个thunk:

export const test = () => => (dispatch, getState) => {
    dispatch(displayMessage({ show: true, text: `test` }));
    setTimeout(() => {
        dispatch(displayMessage({ show: false, text: '' }))
    }, 2000);
}

将被调用,例如dispatch(test())在其他地方。

或者,您还可以从设置文件中 export store do store.dispatch(...) - 但这较少干净。

You could make a thunk:

export const test = () => => (dispatch, getState) => {
    dispatch(displayMessage({ show: true, text: `test` }));
    setTimeout(() => {
        dispatch(displayMessage({ show: false, text: '' }))
    }, 2000);
}

which would be invoked like dispatch(test()) elsewhere.

Or you could also import your store from your setup file and do store.dispatch(...) - but that's a little less clean.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文