javascript - React/Redux 组件未更新
问题描述
我是使用 Redux 的新手,无法弄清楚为什么我的侧边栏组件没有更新以打开抽屉。我可以看到我的操作被调用,但它似乎没有触发我的组件中的任何更新。我试图遵循 Redux 文档,但我看不到我缺少什么,因为我以相同的方式设置了我的代码。
我不想用代码填充帖子,但如果您需要更多信息来帮助解决这个问题,请告诉我。我会很感激任何帮助,谢谢。
解决方案:我在状态对象上使用了错误的属性,所以我的组件没有被更新。它应该是 state.Sidebar.open 而不是 state.open。
const mapStateToProps = (state:any) => ({
open: state.Sidebar.open
});
菜单容器:
import { connect } from 'react-redux';
import { toggleSidebar } from '../actions';
import Menu from '../components/Menu/Menu';
const mapStateToProps = (state:any) => ({
open: state.open ? state.open : false
});
const mapDispatchToProps = (dispatch:any) => ({
toggleSidebar: (open:boolean) => dispatch(toggleSidebar(open))
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Menu);
菜单组件:
class Menu extends React.Component<IMenuProps> {
private handleDrawerOpen = () => {
this.props.toggleSidebar(true);
}
private handleDrawerClose = () => {
this.props.toggleSidebar(false);
}
public render() {
return (
<div>
<MenuBar
handleDrawerOpen={this.handleDrawerOpen}
/>
<SideBar
open={this.props.open}
handleDrawerClose={this.handleDrawerClose}
/>
</div>
);
}
}
侧边栏:
class Sidebar extends React.Component<ISideBarProps> {
public render() {
return (
<div>
<Drawer
open={this.props.open}
onClose={this.props.handleDrawerClose}>
<div
tabIndex={0}
role="button"
>
<AdministrationItems />
</div>
</Drawer>
</div>
);
}
}
*编辑减速器:
const sidebar = (state = { open: false }, action:any) => {
switch (action.type) {
case TOGGLE_SIDEBAR: {
return {
open: action.open
};
}
default: {
return state;
}
}
};
行动:
export const toggleSidebar = (open:boolean) => ({
open,
type: TOGGLE_SIDEBAR,
});
解决方案
解决方案:我在状态对象上使用了错误的属性,所以我的组件没有被更新。它应该是 state.Sidebar.open 而不是 state.open。
const mapStateToProps = (state:any) => ({
open: state.Sidebar.open
});
推荐阅读
- java - 为什么 spring.profiles.active 只读取一些配置文件?
- gdb - 如何从 MacOS 卸载 GDB?
- android - MissingPluginException(未找到通道上的方法的实现)
- javascript - 如何从 mongo db 中插入项目的 id 获取 ObjectId
- svelte - 如何在 Svelte 中使用等待块和更新状态
- ruby-on-rails - 在 Capybara 中单击 data-method="POST" 的链接
- python - 如何在计算相应分位数的熊猫数据框中创建分位数列
- javascript - 如何使用 ajax 发布选定的选项?
- java - 在 Java 程序上运行 Frida 和 JDB 时出现问题
- reactjs - 为什么我的弹出窗口没有显示,默认情况下应该显示?