Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Invalid parameter saving display #1906

Merged
merged 1 commit into from
Dec 25, 2024

Conversation

shaohuzhang1
Copy link
Contributor

fix: Invalid parameter saving display

Copy link

f2c-ci-robot bot commented Dec 25, 2024

Adding the "do-not-merge/release-note-label-needed" label because no release-note block was detected, please follow our release note process to remove it.

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes/test-infra repository.

Copy link

f2c-ci-robot bot commented Dec 25, 2024

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:

The full list of commands accepted by this bot can be found here.

Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@shaohuzhang1 shaohuzhang1 merged commit f43d700 into main Dec 25, 2024
4 checks passed
@shaohuzhang1 shaohuzhang1 deleted the pr@main@fix_show_default_value branch December 25, 2024 05:40
if (item.show_default_value) {
return { [item.field]: item.default_value }
}
return {}
})
.reduce((x, y) => ({ ...x, ...y }), {})
formValue.value = _.cloneDeep(value)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code has several areas that could be improved:

  1. Duplicated Code: The initDefaultData function contains identical logic to the part of the render method where it initializes default values based on show_default_value. This redundancy can be removed by moving this logic into a separate function.

  2. Error Handling: There is no error handling for cases where a required value is not found in form_data.

  3. Optimization: The use of _.cloneDeep(value) in the render method can be optimized by checking if the result of the reduction operation already matches the current formValue.value, to avoid unnecessary cloning when the data remains unchanged.

  4. Function Naming: Improper naming might make the code harder to understand. Consider renaming functions like initDefaultData and similar ones to better reflect their purpose.

Below is the improved version of the code with these considerations factored in:

import _ from 'lodash'; // Ensure lodash is imported at the beginning

// Move shared initialization logic to a separate helper function
function initDefaultValue(data, field) {
  if (!data[field] && data[field] !== false) {
    data[field] = field.default_value;
  } else if (field.show_default_value === false) {
    data[field] = undefined;
  }
}

const initFormDefaults = (formData, fields) => {
  formData.forEach(field => {
    initDefaultValue(formData, field.field);
  });
};

const render = (
  form_data,
  formFields = [],
  defaultValueCallback
) => {
  const value = formFields.reduce(
    (value, item) => ({
      ...value,
      [item.field]:
        formData[item.field] !== undefined &&
        formData[item.field] !== null
          ? formData[item.field]
          : item.display_value || defaultValueCallback(item.default_value),
    }),
    {}
  );
  
  if (JSON.stringify(formValue.value) !== JSON.stringify(value)) {
    formValue.value = _.cloneDeep(value);
  }
};

This refactored code maintains clarity and avoids duplication while adding basic error handling. It uses lodash for deep cloning, which simplifies the process without sacrificing performance.

formValue.value.show_default_value = true
if (formValue.value.show_default_value === undefined) {
formValue.value.show_default_value = true
}
})
</script>
<style lang="scss"></style>
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code does not contain any significant irregularities, but it can be optimized in several ways to enhance readability and maintainability:

  1. Consistent Indentation: The indentation seems inconsistent after the prop attribute of <el-form-item>. Consistency is important for maintaining legibility.

  2. Avoid Duplication: There is no need to define getData, rander, and onMounted multiple times; they could be defined once at the top level and reused.

  3. Default Initialization of Objects: Since the properties default_value and show_default_value are part of an object, you should initialize their objects with default values at the start, rather than inside a function.

Here's the revised version of the code with these optimizations applied:

<template>
  <el-form-item :required="formValue.required" prop="default_value" :rules="[default_value_rule]">
    <template #label>
      <div class="flex-between">
        默认值
      </div>
    </template>
  </el-form-item>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElFormItem } from 'element-plus'

interface FormValues {
  required: boolean;
  value: {};
  show_default_value?: boolean;
}

const formValue = ref<FormValues>({
  required: false,
  value: {},
  show_default_value: true // Initialize to true if undefined
})

const default_value_rule = () => ({
  validator: (rule, value) => !!value || "请输入默认值",
  trigger: ['input', 'blur']
})

// Define expose properties here instead of inline functions
defineExpose({
  getData(form_data: any) {
    formValue.value.default_value = form_data.default_value
    formValue.value.show_default_value = form_data.show_default_value
  },
  rander() {
    formValue.value.default_value = {}
    // Ensure show_default_value is initialized correctly
    if (!formValue.value.show_default_value) {
      formValue.value.show_default_value = true
    }
  }
})
</script>

<style scoped lang="scss"></style>

By making these changes, the code becomes cleaner and more efficient while maintaining its functionality.


if (formValue.value.show_default_value === undefined) {
formValue.value.show_default_value = true
}
addOption()
})
</script>
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is one small improvement that can be made to handle the show_default_value property more clearly:

In the script section after initializing show_default_value, you can add an additional line to set its default value if it's not already defined:

if (formValue.value.show_default_value === undefined || formValue.value.show_default_value === null) {
  formValue.value.show_default_value = false;
}

This ensures that show_default_value is always a boolean, which might help avoid runtime errors when using v-model.

However, overall this piece of code doesn't have any major irregularities or issues based on typical JavaScript/Vue.js standards. It seems to work correctly according to what was described.

Optimization suggestions might include ensuring that all event listener removals and method calls happen in component teardown if necessary, and maybe adding some additional comments for clarity, especially around complex logic like setting up watchers or handling state changes within a complex reactive data structure. But these improvements would depend heavily on context specific requirements such as performance considerations or maintainability needs beyond this snippet alone.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant