如何设置apijson数据反应-select默认值
How to set api json data to react-select default value
我想将 API JSON 数据设置为 react-select
默认值
const [tag, setTag] = useState([])
const [tag_data, setTagData] = useState([[]]);
useEffect
函数调用 API 并获取 JSON 数据
useEffect(() => {
(async () => {
const tag_result = await axios(`${process.env.REACT_APP_API_URL}/tag`);
setTagData(tag_result.data);
})();
}, []);
下面是我的APIJSON数据回复
{id: 1, content_tag: 'Test'}
{id: 2, content_tag: 'test 1'}
{id: 3, content_tag: 'test 2'}
{id: 4, content_tag: 'test 3'}
<Select
id="react-select-tag"
isMulti
options={tag_data}
hideSelectedOptions={false}
getOptionLabel={(option) => option.content_tag}
getOptionValue={(option) => option.content_tag}
// value={tag_data[0]} This set the value but after that i am not able to change another tag
// value={tag} This changed another tag but not set defaultvalue
onChange={(e) => setTag(e)}
defaultValue={tag_data[0]} //This changed another tag but not set defaultvalue
/>
您可以在获取选项后更新状态以设置默认值:
const [tags, setTags] = useState([])
const [tagsData, setTagsData] = useState([]);
useEffect(() => {
(async () => {
const { data } = await axios(`${process.env.REACT_APP_API_URL}/tag`);
setTagsData(data);
setTags([data[0]]);
})();
}, []);
<Select
id="react-select-tag"
isMulti
options={tagsData}
hideSelectedOptions={false}
getOptionLabel={(option) => option.content_tag}
getOptionValue={(option) => option.id} // using id as it is unique
value={tags}
onChange={(selected) => setTags(selected)}
/>
我重命名了几个变量
我想将 API JSON 数据设置为 react-select
默认值
const [tag, setTag] = useState([])
const [tag_data, setTagData] = useState([[]]);
useEffect
函数调用 API 并获取 JSON 数据
useEffect(() => {
(async () => {
const tag_result = await axios(`${process.env.REACT_APP_API_URL}/tag`);
setTagData(tag_result.data);
})();
}, []);
下面是我的APIJSON数据回复
{id: 1, content_tag: 'Test'}
{id: 2, content_tag: 'test 1'}
{id: 3, content_tag: 'test 2'}
{id: 4, content_tag: 'test 3'}
<Select
id="react-select-tag"
isMulti
options={tag_data}
hideSelectedOptions={false}
getOptionLabel={(option) => option.content_tag}
getOptionValue={(option) => option.content_tag}
// value={tag_data[0]} This set the value but after that i am not able to change another tag
// value={tag} This changed another tag but not set defaultvalue
onChange={(e) => setTag(e)}
defaultValue={tag_data[0]} //This changed another tag but not set defaultvalue
/>
您可以在获取选项后更新状态以设置默认值:
const [tags, setTags] = useState([])
const [tagsData, setTagsData] = useState([]);
useEffect(() => {
(async () => {
const { data } = await axios(`${process.env.REACT_APP_API_URL}/tag`);
setTagsData(data);
setTags([data[0]]);
})();
}, []);
<Select
id="react-select-tag"
isMulti
options={tagsData}
hideSelectedOptions={false}
getOptionLabel={(option) => option.content_tag}
getOptionValue={(option) => option.id} // using id as it is unique
value={tags}
onChange={(selected) => setTags(selected)}
/>
我重命名了几个变量