通过传递变量来反应访问类型prop

时间:2017-06-06 14:00:34

标签: reactjs

我有一个包含许多属性的类型,我想知道是否可以使用一个函数来更新任何属性。所以例如我有

export type RequestData = {
  Status: string,
  RequestDate: Moment,
  RequesterName: string,
  RequesterId: number,
  BudgetCategory: string,
  BudgetSubcategory: string,
  BudgetTeamCode: string
}

我可以用这个

更新BudgetSubcategory
interface ConnectedState {
  requestData: Store.RequestData
}

interface ConnectedDispatch {
  updateRequestData: (requestData: Store.RequestData) => void
}

function mapStateToProps(state: Store.All): ConnectedState {
  return {
    requestData: getRequestData(state),
  }
}

function mapDispatchToProps(dispatch: Redux.Dispatch<Store.All>): ConnectedDispatch {
return {
  updateRequestData: (requestData: Store.RequestData) => dispatch(updateRequestData(requestData))
 };
}

class MainContainer extends React.Component<OwnProps & ConnectedState & ConnectedDispatch, {}> {
  constructor(props, context) {
    super(props, context);
  }

  updateBudgetSubcategory = (subcategory: string) => {
    this.props.updateRequestData({...this.props.requestData, BudgetSubcategory: subcategory });
   }
}

我希望能够一次更新这些道具中的任何一个,而无需为每个道具创建单独的功能。是否可以将属性名称与值一起传递以执行类似

的操作
updateRequestDataProperty = (propertyToUpdate: string, value: string) => {
  this.props.updateRequestData({...this.props.requestData, propertyToUpdate: value });
}

1 个答案:

答案 0 :(得分:0)

您想使用computed properties

updateRequestDataProperty = (propertyToUpdate, value) => {
  this.props.updateRequestData({
    ...this.props.requestData,
    [propertyToUpdate]: value  // field name: value of `propertyToUpdate`
  });
};