首页 > 解决方案 > 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>

mapStateToPropsHeader 组件没有道具,我对它的工作方式和工作方式感到非常困惑mapDispatchToProps

如何从使用的子组件更新父组件的状态redux

标签: javascriptreactjsreduxredux-saga

解决方案


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/开始就很复杂


推荐阅读