作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我从 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
我的问题是:
最佳答案
导出 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
关于reactjs - 如何在 React 组件之外访问 Redux 存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64883984/
我是一名优秀的程序员,十分优秀!