gpt4 book ai didi

reactjs - 如何在 React 组件之外访问 Redux 存储

转载 作者:行者123 更新时间:2023-12-04 12:23:19 27 4
gpt4 key购买 nike

我从 Redux 开始,我总是在带有 connect() 和 mapStateToProps() 的组件中使用它,但现在我想每隔 x 次使用 setInterval() 调用我的 API,以检查服务器是否有未存储在 Redux 存储中的新数据,并替换它。
我的方法是创建一个函数来读取存储并像这样更新它:

import { store } from './dir/dir/store.js'

const refresher = async () => {

const state = store.getState();

// Call API, compare 'state.calendar' with calendar from server
// Call store.dispatch() if they are different, then update Redux store

}

export default refresher
我的问题是:
  • 这是使用 Redux 的好习惯吗?
  • 有没有更好的方法来解决这个问题?

  • 谢谢

    最佳答案

    导出 store 并在 vanilla js/ts 文件中使用非常好。
    示例 Redux 存储
    确保export store你创造的

    import { configureStore } from "@reduxjs/toolkit";
    import { slice } from "../features/counterSlice";

    export const store = configureStore({
    reducer: {
    counter: slice.reducer
    }
    });
    在非组件代码中的用法:
    然后您可以 import已创建 store在任何其他代码中
    import { store } from "../App/store";
    import { slice as counterSlice } from "../features/counterSlice";

    export function getCount(): number {
    const state = store.getState();
    return state.counter.value;
    }

    export function incrementCount() {
    store.dispatch(counterSlice.actions.increment());
    }
    功能组件中的传统用法
    import { useDispatch, useSelector } from "react-redux";
    import { RootState } from "../App/store";
    import { slice as counterSlice } from "../features/counterSlice";

    export function Clicker() {
    const dispatch = useDispatch();
    const count = useSelector((state: RootState) => state.counter.value);
    const dispatchIncrement = () => dispatch(counterSlice.actions.increment())
    // ...
    示例切片
    import { createSlice } from "@reduxjs/toolkit";

    export const slice = createSlice({
    name: "counter",
    initialState: { value: 0 },
    reducers: {
    increment: (state) => {
    state.value += 1;
    }
    }
    });
    Demo in Codesandbox
    备注 :您不能将此选项与服务器端渲染一起使用。如果需要支持SSR,可以 use middleware监听调度的 Action 并在其他地方处理。
    进一步阅读
  • What is the best way to access redux store outside a react component? | Stack Overflow
  • Access the Redux Store Outside a React Component | Blog
  • How can I access the store in non react components? | Github Issues
  • 关于reactjs - 如何在 React 组件之外访问 Redux 存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64883984/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com