如何在另一个浏览器标签中打开组件时从Redux中获取状态的值?

huangapple go评论99阅读模式
英文:

How to get the value of state from redux when the component is opened in anothe browser tab?

问题

目前我正在尝试在我的应用程序中实现Redux Toolkit,并在那里创建了存储并将值设置为状态。

但问题是,当我在新标签中打开组件时,我无法访问存储在Redux状态中的值。请建议如何解决这个问题。

以下是供参考的代码:

intex.tsx

  1. import { createRoot } from 'react-dom/client';
  2. import App from './App';
  3. import './styles/css/index.css';
  4. import { Provider } from 'react-redux';
  5. import { store } from './util/redux/store';
  6. const container = document.getElementById('root');
  7. const root = createRoot(container!);
  8. root.render(
  9. <Provider store={store}>
  10. <App />
  11. </Provider>,
  12. );
  13. module.hot?.accept();

gridRowSlice.tsx

  1. import { PayloadAction, createSlice } from '@reduxjs/toolkit';
  2. import { RootState } from './store';
  3. export interface GridState {
  4. activeRow: any;
  5. }
  6. const initialState: GridState = {
  7. activeRow: {},
  8. };
  9. export const dataSlice = createSlice({
  10. name: 'gridRow',
  11. initialState,
  12. reducers: {
  13. move: (state, action) => {
  14. state.activeRow = action.payload;
  15. },
  16. },
  17. });
  18. export const { move } = dataSlice.actions;
  19. export const movedData = (state: RootState) => state.stocksList.activeRow;
  20. export default dataSlice.reducer;

hooks.tsx

  1. import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
  2. import type { RootState, AppDispatch } from './store';
  3. export const useAppDispatch = () => useDispatch<AppDispatch>();
  4. export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

store.tsx

  1. import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit';
  2. import gridRowReducer from './gridRowSlice';
  3. export const store = configureStore({
  4. reducer: {
  5. stocksList: gridRowReducer,
  6. },
  7. });
  8. export type AppDispatch = typeof store.dispatch;
  9. export type RootState = ReturnType<typeof store.getState>;
  10. export type AppThunk<ReturnType = void> = ThunkAction<ReturnType, RootState, unknown, Action<string>>;

在这个组件中,我使用dispatch从表格发送一些数据。

  1. import { move } from '../../util/redux/gridRowSlice';
  2. import { useAppDispatch } from '../../util/redux/hooks';
  3. const table = () => {
  4. useEffect(() => {
  5. dispatch(move(tableData));
  6. });
  7. return (
  8. <div>
  9. //表格代码
  10. </div>
  11. );
  12. };
  13. export default table;

在其他组件中,我想访问更新状态的值,尝试了不同的方法,但都不适用于我。这是我尝试的方法。

  1. import { store } from '../util/redux/store';
  2. import { useAppSelector } from '../util/redux/hooks';
  3. const receiveData = () => {
  4. const data = useAppSelector(movedData);
  5. const view = store.getState();
  6. const view2 = useAppSelector((state) => state.stocksList.activeRow);
  7. useEffect(() => {
  8. console.log(store.getState(), 'data1'); // 返回空对象
  9. console.log(data, 'data2'); // 返回空对象
  10. console.log(view, 'data3'); // 返回空对象
  11. console.log(view2, 'data4'); // 返回空对象
  12. });
  13. return (
  14. <div>
  15. //代码
  16. </div>
  17. );
  18. };
  19. export default receiveData;

注意:我希望在应用程序正在运行时,无论在哪个标签中打开,都能获取状态的值。

英文:

Currently I'm trying to implement the redux toolkit in my application and there i have created the store and set the value to the state.

But the issue is I'm unable to access the value stored in the redux state wen I open the component in new tab. So how it can be done please suggest.

Here is the code for the reference:-

intex.tsx

  1. import { createRoot } from &#39;react-dom/client&#39;;
  2. import App from &#39;./App&#39;;
  3. import &#39;./styles/css/index.css&#39;;
  4. import { Provider } from &#39;react-redux&#39;;
  5. import { store } from &#39;./util/redux/store&#39;;
  6. const container = document.getElementById(&#39;root&#39;);
  7. const root = createRoot(container!);
  8. root.render(
  9. &lt;Provider store={store}&gt;
  10. &lt;App /&gt;
  11. &lt;/Provider&gt;,
  12. );
  13. module.hot?.accept();

gridRowSlice.tsx

  1. import { PayloadAction, createSlice } from &#39;@reduxjs/toolkit&#39;;
  2. import { RootState } from &#39;./store&#39;;
  3. export interface GridState {
  4. activeRow: any;
  5. }
  6. const initialState: GridState = {
  7. activeRow: {},
  8. };
  9. export const dataSlice = createSlice({
  10. name: &#39;gridRow&#39;,
  11. initialState,
  12. reducers: {
  13. move: (state, action) =&gt; {
  14. state.activeRow = action.payload;
  15. },
  16. },
  17. });
  18. export const { move } = dataSlice.actions;
  19. export const movedData = (state: RootState) =&gt; state.stocksList.activeRow;
  20. export default dataSlice.reducer;

hooks.tsx

  1. import { TypedUseSelectorHook, useDispatch, useSelector } from &#39;react-redux&#39;;
  2. import type { RootState, AppDispatch } from &#39;./store&#39;;
  3. export const useAppDispatch = () =&gt; useDispatch&lt;AppDispatch&gt;();
  4. export const useAppSelector: TypedUseSelectorHook&lt;RootState&gt; = useSelector;

store.tsx

  1. import { configureStore, ThunkAction, Action } from &#39;@reduxjs/toolkit&#39;;
  2. import gridRowReducer from &#39;./gridRowSlice&#39;;
  3. export const store = configureStore({
  4. reducer: {
  5. stocksList: gridRowReducer,
  6. },
  7. });
  8. export type AppDispatch = typeof store.dispatch;
  9. export type RootState = ReturnType&lt;typeof store.getState&gt;;
  10. export type AppThunk&lt;ReturnType = void&gt; = ThunkAction&lt;ReturnType, RootState, unknown, Action&lt;string&gt;&gt;;

In this component I have used dispatch to send some data from the table.

  1. import { move } from &#39;../../util/redux/gridRowSlice&#39;;
  2. import { useAppDispatch } from &#39;../../util/redux/hooks&#39;;
  3. const table = () =&gt; {
  4. useEffect(() =&gt; {
  5. dispatch(move(tableData));
  6. });
  7. return (
  8. &lt;div&gt;
  9. //code for table
  10. &lt;/div&gt;
  11. );
  12. };
  13. export default table;

And in other component I want to access the value of updated state and I tried different approach but non is working for me.
This is what I have tried.

  1. import { store } from &#39;../util/redux/store&#39;;
  2. import { useAppSelector } from &#39;../util/redux/hooks&#39;;
  3. const receiveData = () =&gt; {
  4. const data = useAppSelector(movedData);
  5. const view = store.getState();
  6. const view2 = useAppSelector((state) =&gt; state.stocksList.activeRow);
  7. useEffect(() =&gt; {
  8. console.log(store.getState(), &#39;data1&#39;); //returning blank object
  9. console.log(data, &#39;data2&#39;); //returning blank object
  10. console.log(view, &#39;data3&#39;); //returning blank object
  11. console.log(view2, &#39;data4&#39;); //returning blank object
  12. });
  13. return (
  14. &lt;div&gt;
  15. //code
  16. &lt;/div&gt;
  17. );
  18. };
  19. export default receiveData;

Note:- I want to get the value of state in another tab also when its opened while the application is running.

答案1

得分: 1

Redux Store 中存储的数据通常是一个全局 JavaScript 对象。

除非我们将变量持久化存储在某个地方,否则无法从一个标签中访问在另一个标签中声明的变量。例如,将其存储在 LocalStorage 中并通过 storage event 进行同步。

一个简单的解决方案是使用 redux-state-sync 来在多个标签之间同步数据。

如果您的应用程序需要在重新加载后保留数据,您可以使用 redux-persist 进行持久化存储。

参考链接:https://github.com/aohua/redux-state-sync

英文:

The data stored in the Redux Store is typically a Global JS Object.

You cannot access a variable that is declared in a tab from another, until we persist it somewhere. Eg. Storing it in LocalStorage and syncing it via storage event

Simple solution should be using redux-state-sync to sync the data across multiple tabs.

If your application requires the data to be there even after reloading, you can persist it using redux-persist

Reference: https://github.com/aohua/redux-state-sync

huangapple
  • 本文由 发表于 2023年4月4日 17:33:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75927770.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定