【问题标题】:How to dispatch an action that changes the state of a component from its parent component?如何调度一个从其父组件更改组件状态的操作?
【发布时间】:2017-09-11 17:49:23
【问题描述】:

我正在尝试实现一个模式对话框,询问我是否确定是否要删除应用程序中的项目。我有这个组件:

const Options = item => (
    <OptionsMenu>
        <MenuItem onClick={_ => {
            console.log(`Deleting item ${JSON.stringify(item)}`)
        }}>
            <IconButton aria-label="Delete" color="accent">
                <DeleteIcon />
            </IconButton>
            <Typography>
                Eliminar
            </Typography>
        </MenuItem>
        <DeleteDialog
            item={item}
        />
    </OptionsMenu>
)

而我的对话框组件是:

const DeleteDialog = props => (
    <div>
      <Button onClick={() => {
        this.props.openDeleteDialog(this.props.item)
      }}>Delete</Button>
      <Dialog open={this.props.open} onRequestClose={this.props.cancelDeleteData}>
        <DialogTitle>{"DELETE"}</DialogTitle>
        <DialogContent>
          <DialogContentText>
            Are you sure you want to delete the item: {this.props.item.name}
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={this.props.cancelDeleteData} color="primary">
            Cancel
          </Button>
          <Button onClick={this.props.deleteData(this.props.item)} color="primary">
            Delete
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );

const mapStateToProps = state => ({
open: state.item.delete.open,
})

const mapDispatchToProps = dispatch => ({
...deleteDispatchesForScope(scopes.ITEM, dispatch)
})

我想要的是从 Options 组件调度 openDeleteDialog 操作,该操作将打开状态设置为 true,以便我可以在其他组件中重用模态对话框。 我为此使用 react-redux 和 material-ui v1。

【问题讨论】:

    标签: react-redux material-ui


    【解决方案1】:

    为了有更多可重用的组件,我会将DeleteDialogOptionsMenu 解耦,并依靠ParentComponent 来传递每个孩子所需的道具:

    <ParentComponent>
      <OptionsMenu>
        <MenuItem onClick={this.props.openDeleteDialog}>Eliminar</MenuItem>
      </OptionsMenu>
      <DeleteDialog 
        open={this.props.isDeleteDialogOpen} 
        item={this.props.item} 
        onDelete={this.props.deleteData} 
      />
    </ParentComponent>
    

    【讨论】:

      猜你喜欢
      • 2016-12-21
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      • 2020-10-12
      相关资源
      最近更新 更多