首页 > 解决方案 > React-Redux 用一个切换连接两个独立的组件

问题描述

我知道这可能是一个非常基本的问题,但它更像是“我不理解文档,请帮助我”类型的问题。

我正在尝试使用 React-Redux 连接两个组件:第一个是侧边栏,第二个是单击侧边栏中的按钮时应该出现的模式。这些组件在任何父子关系中都不相关(除了根),所以我认为 redux 是最好的选择。

我已经阅读了所有的 redux(和 react-redux)文档,并且理解了 redux 的核心概念,但是我无法理解如何在我的组件中实现它们。

基本上我想要侧边栏中的一个按钮来切换存储的状态(真/假就足够了),并且根据该状态,模态将出现(state==true => display:block)并通过模态()中的按钮消失state==false => display:none

我认为我需要的是切换状态的操作,例如:

const modalsSlice = createSlice({
    name: 'modals',
    initalState,
    reducers: {
        toggleModal(state, action){
            state = !state;
        }
    }
});

然后使用以下方法连接两个组件中的操作(我在类中编写组件而不是函数):

const toggleModal = {type: 'modals/toggleModal', payload: ''};
const mapStateToProps = state => state.showHideModal;

export default connect(mapStateToProps, toggleModal)(Component);

现在,假设我到目前为止是正确的,我不确定如何继续。即我应该如何接收和更改组件本身?当然,我需要将一个函数放在一个带有onClick={foo}监听器的按钮中,但是foo假设如何接收和处理状态?我想在showHideModal某处初始化状态吗?在根组件中?在配置商店时?

任何帮助将非常感激。

标签: javascriptreactjsreduxreact-redux

解决方案


状态初始化

您应该showHideModal在切片本身中初始化状态。此外,它应该被命名为showModal或者hideModal为了更好地解释这个状态所做的事情。


const modalSlice = createSlice({
    name: 'modal',
    initialState: {
      showModal: false,
    },
    reducers: {
      toggleModal(state){
          state.showModal = !state.showModal;
      }
    }
});

export const { toggleModal } = modalSlice.actions;

侧边栏组件

事件onClick处理程序需要通过 mapDispatchToProps显式传递。

import { toggleModal } from './modalSlice';

class Sidebar extends Component {
  handleClick = () => {
    const { toggleModal } = this.props;
    toggleModal();
  }

  render() {
    return (
      <div>
        {/* rest of JSX */}
        <button onClick={this.handleClick}>Toggle Modal</button>
        {/* rest of JSX */}
      </div>
    );
  }
}

const mapDispatchToProps = {
  toggleModal,
};

export default connect({}, mapDispatchToProps)(Sidebar);

模态

注意:您不能像以前那样直接从 state 访问属性state.showHideModal;。您需要先访问切片,然后访问其中存在的属性state.modal.showHideModal;


class Modal extends Component {
  handleClick = () => {
    const { toggleModal } = this.props;
    toggleModal();
  }

  render() {
    const { showModal } = this.props;

    return (
      <>
        {showModal ? (
          <div>
            <button onClick={this.handleClick}>Close</button>
          </div>
        ) : null}
      </>
    );
  }
}

const mapDispatchToProps = {
  toggleModal,
};

const mapStateToProps = state => ({
  showModal: state.modal.showModal,
});

export default connect(mapStateToProps, mapDispatchToProps)(Modal);

更新

来,Redux 抛出以下警告的原因:

在路径中的操作中检测到​​不可序列化的值:payload

这是因为SyntheticEvent作为有效负载传递给操作。为了解决这个问题,您需要将toggleModal调用从移动onClick prop到单独的处理函数。供您参考,请检查ModalSideBarhandleClick中的功能。


推荐阅读