如何在react中观察字段(动态添加 useEffect)?

IT技术 javascript reactjs
2021-05-09 11:13:03

我正在尝试观看具有字段的字段watch:true。换句话说,我想useEffect动态添加。我有一个 json(来自服务器)。我想观看字段值(具有属性watch:true)。使用它的值我想更新其他字段值。

这是我的代码

https://codesandbox.io/s/crimson-violet-uxbzd

看到这个对象有watch: true,所以我需要观察或检查它的值是否改变

 {
     label: "First",
     name: "first",
     type: "select",
     remove: true,
     watch: true,
     options: ["", "one", "two"]
},

如果它的值被更改,则调用此函数

const getSecondDropdownValue = function(value) {
    return new Promise((resolve, reject) => {
      if (value === "one") {
        setTimeout(function() {
          resolve(["three", "four"]);
        }, 1000);
      }

      if (value === "two") {
        setTimeout(function() {
          resolve(["five", "six"]);
        }, 1000);
      }
    });
  };

任何更新?。

1个回答

检查项目是否具有watch属性,如果它确实传递getSecondDropdownValueonChange选择选项的事件。就像是

<select onChange={hasWatch ? getSecondDropdownValue : () => {}}>...</select>

创建一个将呈现选择选项的组件。

// options = array of list options
// onChange = onchange event handler
// name = name of the select
const Option = ({ options, onChange, name }) =>
  (options.length && (
    <select onChange={(e) => onChange(e.target.value, name)}>
      {Array.isArray(options) &&
        options.map((option, index) => (
          <option value={option} key={option + index}>{option}</option>
        ))}
    </select>
  )) ||
  false;

添加 useState 用于存储来自 api 的数据。

// initial data from the api
const [data, updateData] = useState(apiData);

// update select options and the list
const updateSelectData = (list, updated) => {

    const index = list.findIndex(item => item.name === updated.name);
    return [
      ...list.slice(0, index),
      Object.assign({}, list[index], updated),
      ...list.slice(index + 1)
    ];
  };

getSecondDropdownValue 函数

const getSecondDropdownValue = function(value, name) {
  const updated = data.find(
    item => item.dependentField && item.dependentField[0] === name
  );

  // return new Promise((resolve, reject) => {
  if (value === "one") {
    // setTimeout(function() {
    // resolve(["three", "four"]);
    // }, 1000);
    updated.options = ["three", "four"];
  }

  if (value === "two") {
    // setTimeout(function() {
    // resolve(["five", "six"]);
    // }, 1000);
    updated.options = ["five", "six"];
  }
  // });

  updateData(updateSelectData(data, updated));
};

例子