在反应的下拉列表中显示获取的数据的问题
issues in displaying fetched data in a dropdown in react
我正在 useEffect 挂钩中从服务器获取用户列表,并试图将其显示在 HTML select 下拉列表中。像这样,codesandbox link
如您所见,下拉列表中没有显示任何内容。但与此同时,所有数据都显示在下面的列表中。
我尝试在没有任何库的情况下实现正常的 HTML select,目前正在使用 react-select。我也试过这个:
{ posts? (<Select options={posts}) : null }
但是没有成功。我在这里错过了什么?如何在下拉列表中显示从服务器获取的数据?
您需要在 Select
上添加一个 getOptionLabel
道具。
<Select options={posts} getOptionLabel={item=>item}/>
getOptionLabel typeof getOptionLabel = (option) => string
将选项数据解析为字符串,以供组件显示为标签
react-select 接受值和标签属性。更新您的字段或使用与 react-select 接受相同的密钥。
export default function App() {
const [posts, setPosts] = useState([]);
useEffect(() => {
const config = {
"Content-Type": "application/json"
};
const url = `https://jsonplaceholder.typicode.com/posts`;
axios.get(url, config).then(res => {
setPosts(res.data);
});
}, []);
let updatedData = posts.map(post=> ({...post, label:post.title, value:post.title}))
console.log(posts);
return (
<div className="App">
<h1>Hello React CodeSandbox</h1>
<div className="side-by-side">
<h3>Latest Posts</h3>
<div className="side-by-side">
<span style={{ paddingRight: "20px" }}>Show Posts</span>
</div>
</div>
<Select options={updatedData} />
</div>
);
}
我正在 useEffect 挂钩中从服务器获取用户列表,并试图将其显示在 HTML select 下拉列表中。像这样,codesandbox link 如您所见,下拉列表中没有显示任何内容。但与此同时,所有数据都显示在下面的列表中。
我尝试在没有任何库的情况下实现正常的 HTML select,目前正在使用 react-select。我也试过这个:
{ posts? (<Select options={posts}) : null }
但是没有成功。我在这里错过了什么?如何在下拉列表中显示从服务器获取的数据?
您需要在 Select
上添加一个 getOptionLabel
道具。
<Select options={posts} getOptionLabel={item=>item}/>
getOptionLabel typeof getOptionLabel = (option) => string
将选项数据解析为字符串,以供组件显示为标签
react-select 接受值和标签属性。更新您的字段或使用与 react-select 接受相同的密钥。
export default function App() {
const [posts, setPosts] = useState([]);
useEffect(() => {
const config = {
"Content-Type": "application/json"
};
const url = `https://jsonplaceholder.typicode.com/posts`;
axios.get(url, config).then(res => {
setPosts(res.data);
});
}, []);
let updatedData = posts.map(post=> ({...post, label:post.title, value:post.title}))
console.log(posts);
return (
<div className="App">
<h1>Hello React CodeSandbox</h1>
<div className="side-by-side">
<h3>Latest Posts</h3>
<div className="side-by-side">
<span style={{ paddingRight: "20px" }}>Show Posts</span>
</div>
</div>
<Select options={updatedData} />
</div>
);
}