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

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

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

问题

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

但问题是,当我在新标签中打开组件时,我无法访问存储在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>>;

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

import { move } from '../../util/redux/gridRowSlice';
import { useAppDispatch } from '../../util/redux/hooks';

const table = () => {
  useEffect(() => {
    dispatch(move(tableData));
  });

  return (
    <div>
      //表格代码
    </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'); // 返回空对象
    console.log(data, 'data2'); // 返回空对象
    console.log(view, 'data3'); // 返回空对象
    console.log(view2, 'data4'); // 返回空对象
  });

  return (
    <div>
      //代码
    </div>
  );
};
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

import { createRoot } from &#39;react-dom/client&#39;;

import App from &#39;./App&#39;;
import &#39;./styles/css/index.css&#39;;
import { Provider } from &#39;react-redux&#39;;
import { store } from &#39;./util/redux/store&#39;;

const container = document.getElementById(&#39;root&#39;);
const root = createRoot(container!);

root.render(
  &lt;Provider store={store}&gt;
    &lt;App /&gt;
  &lt;/Provider&gt;,
);

module.hot?.accept();

gridRowSlice.tsx

import { PayloadAction, createSlice } from &#39;@reduxjs/toolkit&#39;;
import { RootState } from &#39;./store&#39;;

export interface GridState {
  activeRow: any;
}

const initialState: GridState = {
  activeRow: {},
};

export const dataSlice = createSlice({
  name: &#39;gridRow&#39;,
  initialState,
  reducers: {
    move: (state, action) =&gt; {
      state.activeRow = action.payload;
    },
  },
});

export const { move } = dataSlice.actions;

export const movedData = (state: RootState) =&gt; state.stocksList.activeRow;
export default dataSlice.reducer;

hooks.tsx

import { TypedUseSelectorHook, useDispatch, useSelector } from &#39;react-redux&#39;;
import type { RootState, AppDispatch } from &#39;./store&#39;;

export const useAppDispatch = () =&gt; useDispatch&lt;AppDispatch&gt;();
export const useAppSelector: TypedUseSelectorHook&lt;RootState&gt; = useSelector;

store.tsx

import { configureStore, ThunkAction, Action } from &#39;@reduxjs/toolkit&#39;;
import gridRowReducer from &#39;./gridRowSlice&#39;;

export const store = configureStore({
  reducer: {
    stocksList: gridRowReducer,
  },
});

export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType&lt;typeof store.getState&gt;;
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.

import { move } from &#39;../../util/redux/gridRowSlice&#39;;
import { useAppDispatch } from &#39;../../util/redux/hooks&#39;;

const table = () =&gt; {

useEffect(() =&gt; { 
dispatch(move(tableData)); 
});

  return (
      &lt;div&gt;
        //code for table
      &lt;/div&gt;
  );
};
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.

import { store } from &#39;../util/redux/store&#39;;
import { useAppSelector } from &#39;../util/redux/hooks&#39;;


const receiveData = () =&gt; {
const data = useAppSelector(movedData);
const view = store.getState();
const view2 = useAppSelector((state) =&gt; state.stocksList.activeRow);

useEffect(() =&gt; { 
console.log(store.getState(), &#39;data1&#39;); //returning blank object
console.log(data, &#39;data2&#39;); //returning blank object
console.log(view, &#39;data3&#39;); //returning blank object
console.log(view2, &#39;data4&#39;);  //returning blank object
    });
  return (
      &lt;div&gt;
        //code
      &lt;/div&gt;
  );
};
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:

确定