简体   繁体   English

如何将值推入状态中的数组

[英]How to push value into an Array in State

Currently working on a create-blog form that requires an input named tags that needs to be an array in my state.目前正在处理一个创建博客表单,它需要一个名为标签的输入,在我的状态下需要是一个数组。

I am using the .push method to push my entries into an empty array that I have in my state.我正在使用.push方法将我的条目推送到我所在州的空数组中。

It works, I am able to create a new blog but there area multiple arrays under tags instead of 1 .它有效,我可以创建一个新博客,但是标签下有多个数组而不是1

Example looks like: ["ne"] ["w] [bl"] ["logs"] instead of just 1 array [new blogs].示例如下所示: ["ne"] ["w] [bl"] ["logs"]而不是 1 个数组 [new blogs]。 Also if I backspace, my previous entries save in the state.此外,如果我退格,我以前的条目会保存在状态中。

Tried the .push method but it just keeps creating multiple arrays.尝试了.push方法,但它只是不断创建多个数组。

state = {
  title: "",
  shortTitle: "",
  content: "",
  shortDescription: "",
  slug: "",
  metaData: {
    dateStart: "",
    section: 0
  },
  statusId: 0,
  primaryImage: "",
  tags: [],
  modal: true
};

handleTags = event => {
  let tags = [...this.state.tags];
  tags.push(event.target.value);
  this.setState({ tags });
};

<FormGroup>
  <Label for="tags">Tags</Label>
  <Input
    type="text"
    name="tags"
    value={this.state.handleTags}
    onChange={this.handleTags}
  />
</FormGroup>;

I can create a blog without any issues if I do not backspace any of my entries.如果我不退格任何条目,我可以毫无问题地创建博客。 I am hoping to have 1 array for the entry I input in my form instead of multiple ones.我希望我在表单中输入的条目有 1 个数组,而不是多个数组。

For one, I don't see this in your state: this.state.handleTags.一方面,我在你的州没有看到这个:this.state.handleTags。

I see a function but no variable in your state with that name.我看到一个函数,但在您的状态中没有具有该名称的变量。

When you do create that state variable, make sure it is not an array.创建该状态变量时,请确保它不是数组。

You could also try deconstructing the tags array like so:您也可以尝试像这样解构标签数组:

handleTags = event => {
   let tags = [...this.state.tags, event.target.value ];
   this.setState({ tags });
};

Other than that I would need to see more code.除此之外,我需要查看更多代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM