javascript - 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
某处初始化状态吗?在根组件中?在配置商店时?
任何帮助将非常感激。
解决方案
状态初始化
您应该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
到单独的处理函数。供您参考,请检查Modal和SideBarhandleClick
中的功能。
推荐阅读
- bash - 在 bash 脚本上设置一个 cron 但它没有运行
- c# - C# 将字符串解析为 Func
- javascript - 对日期名称元素进行排序以获取映射值
- objective-c - Final cut pro 自定义共享到我的未响应的可编写脚本的应用程序
- docker - Docker 上的 JavaFX - 初始化 QuantumRenderer 时出错:找不到合适的管道
- javascript - HTML 2d 画布作为 webgl 画布上的纹理
- r - 使用 R 语言为 arima 生成示例路径
- ios - 如何使用联系人 UI 快速打开现有联系人的编辑联系人 UI
- windows - 批处理文件 - 设置参数值,然后传递给 exe
- r - 在 R rethinking 包中,嵌套索引的语法是什么?