I'm currently working on a tag feature in React and I am not sure how to update the tags.
In 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
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 "]
. The console.log(this.state.tag)
after the this.setState
also outputs and array, but always one behind the console.log(tags)
. ie, when console.log(tags)
outputs ["1"]
, console.log(this.state.tag)
outputs [""]
. when console.log(tags)
outputs ["1", "2"]
, console.log(this.state.tag)
outputs ["1"]
. Also, when I remove the tags, the state doesn't update. 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
this.setState({ tag: tags }, () => {
console.log(this.state.tag)
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.