[英]ReactJS how to update array state?
我目前正在研究 React 中的標簽功能,但我不確定如何更新標簽。
在 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;
在 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>
);
}
}
console.log(tags)
只輸出容器中所有標簽的數組,如下所示: ["1 ", "2 ", "3 ", "4 "]
。 this.setState 之后的console.log(this.state.tag)
this.setState
輸出和數組,但總是在console.log(tags)
后面。 即,當console.log(tags)
輸出["1"]
時, console.log(this.state.tag)
輸出[""]
。 當console.log(tags)
輸出["1", "2"]
時, console.log(this.state.tag)
輸出["1"]
。 此外,當我刪除標簽時,state 不會更新。 我怎樣才能解決這個問題?
在合成事件中,setState 異步更新 state。setState 后,控制台的值始終是更新前的值
this.setState({ tag: tags }, () => {
console.log(this.state.tag)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.