javascript - React/Redux - 从子组件更新父组件的状态
问题描述
我有 2 个组件:已开发的react
应用程序中的 Header 和 Child 使用redux-saga
.
Header 组件有 2 个 material-ui Select 组件。现在,当我路由到子组件时,我想通过更新它的状态来禁用 Header 中的那些 2 Select 组件。
App.js
const App = ({ store }) => {
return (
<ThemeProvider theme={theme}>
<Provider store={store}>
<Header />
<Router />
<Footer />
</Provider>
</ThemeProvider>
);
};
Router.js
<Route
exact
path={`${url}BatchFileRawDataDashboard`}
component={Child}
/>
Header.js
<Select
style={{ width: 112 }}
value={this.state.selectedCycle}
autoWidth={true}
disabled={this.disableCycle.bind(this)}
>
{cycleDateItem}
</Select>
mapStateToProps
Header 组件没有道具,我对它的工作方式和工作方式感到非常困惑mapDispatchToProps
。
如何从使用的子组件更新父组件的状态redux
?
解决方案
mapStateToProps = 将 redux 存储状态放入 props
mapDispatchToProps = 将 redux 动作放入 props
所以在孩子身上,你想调用一个动作,通过 mapDispatchToProps 更新商店
然后在要使用 mapStateToProps 读取此更新值的父级上
// PARENT READ DATA
const mapStateToProps = (store) => ({
parentData: store.parentData,
})
// CHILD ACTION TO UPDATE STORE
// the function here triggers a action which triggers a reducer
const mapDispatchToProps = dispatch => ({
updateParentAction: data => dispatch(some_action_name(data)),
})
我建议阅读 redux 的工作原理,一旦你得到它就很简单,但从https://www.valentinog.com/blog/redux/开始就很复杂
推荐阅读
- go - 没有这样的工具“asm”
- css - 如何在引导 vue 上制作按钮减号和加号?
- java - 添加软链接属性spring-data-rest?
- nginx - 如何在 nginx 服务器中只监听 443
- reporting-services - SSRS - 分隔字符串的一部分并返回
- php - array_key_exists 和 ?? 在 php 7.x 中
- javascript - 如果它们有索引,如何登录控制台javascript数组项目属性
- azure - 一对一处理服务总线队列消息
- kubernetes - Helm chart 在 configmap 更改时重新启动 pod
- c - C、MPI:程序未终止且未打印数字