【问题标题】:Component verification using Redux使用 Redux 进行组件验证
【发布时间】:2021-11-21 19:47:17
【问题描述】:

在反应中,为了验证和展示一个组件,我们这样做:

const [state, setState] = useState(false);

<button ... onClick={() => setState(true)} />

{state && <MyComponent />}

但是如果我想更改此代码以使用 redux 怎么办?

【问题讨论】:

  • 你可以在 redux 中存储你的布尔调用状态。

标签: javascript reactjs typescript redux react-redux


【解决方案1】:

您可以使用react-redux 来实现这一点,即使您还没有设置商店需要一些样板代码。

您可以执行以下操作:

import { useSelector, useDispatch } from 'react-redux'
import { showViewAction } from './viewDisplaySlice'

export const MyComponent = () => {
  const shouldDisplayComponent = useSelector(state => state.shouldDisplay);
  const dispatch = useDispatch();

  return (
    ....
        <button
          onClick={() => dispatch(showViewAction())}
        >
          ...
        </button>
        { shouldDisplayComponent && <MyViewComponent /> }
    </div>
  );
};

您可能会发现快速入门指南有助于设置商店和使用 react-redux: https://redux.js.org/tutorials/quick-start

【讨论】:

  • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
  • @eglease 你有一个有效的观点,我更新了我的答案。
猜你喜欢
  • 2018-01-02
  • 2018-01-10
  • 2020-07-05
  • 1970-01-01
  • 1970-01-01
  • 2021-05-09
  • 2017-06-25
  • 2019-05-25
  • 1970-01-01
相关资源
最近更新 更多