简体   繁体   English

ReactJS 如何更新数组 state?

[英]ReactJS how to update array state?

I'm currently working on a tag feature in React and I am not sure how to update the tags.我目前正在研究 React 中的标签功能,但我不确定如何更新标签。

In TagsInput.js在 TagsInput.js 中

import React, { useState } from "react";
import CancelIcon from "@material-ui/icons/Cancel";

import "../../css/TagsInput.css";

function TagsInput(props) {
  const [tags, setTags] = useState(props.tags);
  const removeTags = (indexToRemove) => {
    setTags([...tags.filter((_, index) => index !== indexToRemove)]);
  };

  const addTags = (event) => {
    if (event.target.value !== "") {
      setTags([...tags, event.target.value]);
      props.selectedTags([...tags, event.target.value]);
      event.target.value = "";
    }
  };

  return (
    <div className="tags-input">
      <ul id="tags">
        {tags.map((tag, index) => (
          <li key={index} className="tag">
            <span className="tag-title">{tag}</span>
            <CancelIcon className="tag-close-icon" onClick={() => removeTags(index)} />
          </li>
        ))}
      </ul>
      <input
        type="text"
        onKeyUp={(event) => (event.key === " " ? addTags(event) : null)}
        placeholder="Press space to add tags"
      />
    </div>
  );
}

export default TagsInput;

In Post.js在 Post.js 中

import React, { Component } from "react";

class Post extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tag: ["test tag"],
    };
  }

  render() {
    const selectedTags = (tags) => {
      console.log(tags);
      this.setState({ tag: tags });
      console.log(this.state.tag);
    };

    const { subject, tag, question } = this.state;

    return (
      <div className="post">
        <div className="post__container">
          <form onSubmit={this.handleSubmit}>
            <div className="post__textInput">
              <TagsInput
                selectedTags={selectedTags}
                tags={[]}
              />
            </div>
          </form>
        </div>
      </div>
    );
  }
}

The console.log(tags) just outputs an array of all the tags in the container, something like this: ["1 ", "2 ", "3 ", "4 "] . console.log(tags)只输出容器中所有标签的数组,如下所示: ["1 ", "2 ", "3 ", "4 "] The console.log(this.state.tag) after the this.setState also outputs and array, but always one behind the console.log(tags) . this.setState 之后的console.log(this.state.tag) this.setState输出和数组,但总是在console.log(tags)后面。 ie, when console.log(tags) outputs ["1"] , console.log(this.state.tag) outputs [""] .即,当console.log(tags)输出["1"]时, console.log(this.state.tag)输出[""] when console.log(tags) outputs ["1", "2"] , console.log(this.state.tag) outputs ["1"] .console.log(tags)输出["1", "2"]时, console.log(this.state.tag)输出["1"] Also, when I remove the tags, the state doesn't update.此外,当我删除标签时,state 不会更新。 How can I fix this?我怎样才能解决这个问题?

In synthetic events, setState update the state asynchronously.After you setState, the console's value is always the value before the update在合成事件中,setState 异步更新 state。setState 后,控制台的值始终是更新前的值

this.setState({ tag: tags }, () => {
  console.log(this.state.tag)
})

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

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