在某些组件中使用react,redux(thunk)使用全局状态和局部状态

时间:2018-12-04 12:14:38

标签: reactjs redux react-redux redux-thunk

我正在开发一个包含多个组件的应用程序。 组件A:将它们之间的对象关系节点显示为边缘。 我通过在全局状态/存储区中调用Component As componentDidMount()函数中的一个函数,使用(基于redux-thunk)从api加载数据。 另外,我必须仅基于存储在数据中的对象的某些字段来创建节点。

组件B: 我的意图是,如果单击某个节点,则将另一个组件(该节点的详细视图)添加到组件B。对于此“详细视图”,我需要对象的其他(additionall)字段。

到目前为止,我的问题是我还需要组件A的本地状态。原因是我还必须添加不应传播到全局状态/存储的临时节点。

所以我的问题是: 您能给我一个建议,我应该只选择组件A和组件B中一个对象的必填字段吗?

如何处理组件B中需要全局状态和局部状态的情况?

1 个答案:

答案 0 :(得分:0)

一种解决方案是创建一个商店,并订阅对该商店的更改的更改。

下一个代码使用redux示例。

// ./globalState.js
import { useEffect, useState } from 'react'; 
import { createStore } from 'redux';

const store = createStore(function counter(state = 0, action) {
  switch (action.type) {
  case 'INCREMENT':
    return state + 1;
  case 'DECREMENT':
    return state - 1;
  default:
    return state;
  }
});

export const useGlogalStore = () => {
  const [state, setState] = useState();

  useEffect(() => {
    return store.subscribe(() => setState(store.getState()));
  }, [store]);

  return [state, store.dispatch];
}

然后在您的应用中仅使用useGlogalStore()来读取状态。

示例。

import { useGlogalStore } from './globalState.js';

export const App = () => {
  const [state, dispatch] = useGlogalStore();
  return <div>
    Count: {state}

    <button onClick={() => dispatch({ type: 'INCREMENT' })}>Up</button>
    <button onClick={() => dispatch({ type: 'DECREMENT' })}>Down</button>
  </div>
}