我有下面的代码,我想在其中创建标签列表。在此示例中,我正在获取标签列表setAllTags()
然后是一些可用的标签setAvailableTags()
.
那么我遇到的问题是当setAvailableTags()
运行它将删除在中获取的标签setAllTags()
。好像是我设定的状态setAllTags()
不使用时setAvailableTags()
是设置它的状态。
知道我能做些什么来解决这个问题吗?
https://codesandbox.io/s/rj40lz6554 https://codesandbox.io/s/rj40lz6554
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
const Search = () => {
const [tags, setTags] = useState({
all: [],
available: []
});
const setAllTags = () => {
const all = ["tag 1", "tag 2", "tag 3"];
const newValue = {
...tags,
all
};
console.log("setting all tags to ", newValue);
setTags(newValue);
};
const setAvailableTags = () => {
const available = ["tag 1", "tag 2"];
const newValue = {
...tags,
available
};
console.log("setting available tags to", newValue);
setTags(newValue);
};
useEffect(setAllTags, []);
useEffect(setAvailableTags, []);
return (
<div>
<div>
<select placeholder="Tags">
{tags.all.map((tag, i) => (
<option key={tag + i} value={tag}>
{tag}
</option>
))}
</select>
</div>
</div>
);
};
const App = () => {
return (
<div>
<h1>Hello React!</h1>
<Search />
</div>
);
};
ReactDOM.render(<App />, document.getElementById("app"));
控制台记录为
setting all tags to Object {all: Array[3], available: Array[0]}
setting available tags to Object {all: Array[0], available: Array[2]}