目前我正在尝试在我的应用程序中实现redux工具包,在那里我已经创建了存储并将值设置为状态。
但问题是,当我在新选项卡中打开组件时,我无法访问存储在redux状态中的值。因此,请建议如何做。
下面是引用的代码:-
intex.tsx
import { createRoot } from 'react-dom/client';
import App from './App';
import './styles/css/index.css';
import { Provider } from 'react-redux';
import { store } from './util/redux/store';
const container = document.getElementById('root');
const root = createRoot(container!);
root.render(
<Provider store={store}>
<App />
</Provider>,
);
module.hot?.accept();
gridRowSlice.tsx
import { PayloadAction, createSlice } from '@reduxjs/toolkit';
import { RootState } from './store';
export interface GridState {
activeRow: any;
}
const initialState: GridState = {
activeRow: {},
};
export const dataSlice = createSlice({
name: 'gridRow',
initialState,
reducers: {
move: (state, action) => {
state.activeRow = action.payload;
},
},
});
export const { move } = dataSlice.actions;
export const movedData = (state: RootState) => state.stocksList.activeRow;
export default dataSlice.reducer;
hooks.tsx
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from './store';
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
store.tsx
import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit';
import gridRowReducer from './gridRowSlice';
export const store = configureStore({
reducer: {
stocksList: gridRowReducer,
},
});
export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<ReturnType, RootState, unknown, Action<string>>;
在这个组件中,我使用调度从表中发送一些数据。
import { move } from '../../util/redux/gridRowSlice';
import { useAppDispatch } from '../../util/redux/hooks';
const table = () => {
useEffect(() => {
dispatch(move(tableData));
});
return (
<div>
//code for table
</div>
);
};
export default table;
在其他组件中,我想访问更新状态的值,我尝试了不同的方法,但非为我工作。这是我试过的。
import { store } from '../util/redux/store';
import { useAppSelector } from '../util/redux/hooks';
const receiveData = () => {
const data = useAppSelector(movedData);
const view = store.getState();
const view2 = useAppSelector((state) => state.stocksList.activeRow);
useEffect(() => {
console.log(store.getState(), 'data1'); //returning blank object
console.log(data, 'data2'); //returning blank object
console.log(view, 'data3'); //returning blank object
console.log(view2, 'data4'); //returning blank object
});
return (
<div>
//code
</div>
);
};
export default receiveData;
注意:-我想在另一个选项卡中获得状态的值,当它在应用程序运行时打开。
存储在Redux Store中的数据通常是一个全局JS对象。
你不能从另一个选项卡访问在一个选项卡中声明的变量,除非我们将它保存在某个地方。如。将其存储在LocalStorage中并通过存储事件同步
简单的解决方案应该是使用redux-state-sync
在多个选项卡之间同步数据。
如果您的应用程序要求即使在重新加载后数据仍然存在,您可以使用redux-persist
将其持久化。参考:https://github.com/aohua/redux-state-sync