如何正确更改对象数组的状态值?

时间:2019-06-07 16:27:41

标签: reactjs state svelte

想象一下这个变量:

let myArray = [
        {
            name: "animal",
            value: "",
        },
        {
            name: "fruit",
            value: "",
        },
        (...)
];
  1. myArray是固定的-它是硬编码的,其长度不会改变,但是它是一个由10个元素组成的长数组。用户将仅通过html输入更新myArray对象的。基于上述情况,myArray是否可以视为Svelte中的状态?

  2. 下面是在Svelte中更改myArray状态的正确方法吗?

(...)
myArray.forEach(element => { 
    if (element.name === name) element.value = value;
});

  1. 我有一个按钮状态,其disabled属性取决于myArray中所有具有某些值的元素。我可以使用Sveltes $: btnIsDisabled反应式语句来实现该目标吗?如何实现?
<button type="submit" disabled={btnIsDisabled}>
    Submit me
</button>

1 个答案:

答案 0 :(得分:2)

我假设您打算使用数组作为组件状态。并且您有一个与每个字段对应的输入。

尝试类似这样的操作:https://codesandbox.io/s/magical-fog-tfq3q

class App extends React.Component {
  state = {
    favorites: [
      { name: "animal", value: "" },
      { name: "city", value: "" },
      { name: "song", value: "" },
      { name: "place", value: "" },
      { name: "food", value: "" },
      { name: "sport", value: "" }
    ],
    emptyFields: null
  };

  handleOnChange = event => {
    const { favorites } = this.state;

    let updatedArr = favorites.map(favorite => {
      if (favorite.name === event.target.name) {
        return {
          ...favorite,
          value: event.target.value
        };
      } else {
        return favorite;
      }
    });

    let emptyFields = updatedArr.filter(favorite => {
      return favorite.value.length === 0;
    });

    this.setState({
      ...this.state,
      favorites: updatedArr,
      emptyFields: emptyFields
    });
  };

  createFavoriteInputs = () => {
    const { favorites } = this.state;
    return favorites.map(favorite => {
      return (
        <div key={favorite.name}>
          <label>{favorite.name} :</label>
          <input
            value={favorite.value}
            name={favorite.name}
            onChange={this.handleOnChange}
          />
        </div>
      );
    });
  };
  render() {
    const { emptyFields } = this.state;
    return (
      <div>
        {this.createFavoriteInputs()}
        <button
          disabled={!emptyFields || emptyFields.length > 0 ? true : false}
        >
          Submit
        </button>
        {!emptyFields ||
          (emptyFields.length > 0 && (
            <div>
              The following fields are required:
              <ul>
                {this.state.emptyFields.map(field => {
                  return <li key={field.name}>{field.name}</li>;
                })}
              </ul>
            </div>
          ))}
      </div>
    );
  }
}

所以现在处于emptyFields状态,如果有disabled,我们有一个emptyFields按钮。

handleOnChange()帮助我们导航正确的状态值以在数组中进行更新,每当我们对表单中的输入之一进行更新时,便会在状态下创建一个新的数组。