在反应下拉列表中显示获取的数据中的问题

时间:2020-05-05 17:55:32

标签: javascript reactjs react-functional-component

我正在从useEffect挂钩中的服务器中获取用户列表,并尝试在HTML select下拉列表中显示它。像这样codesandbox link 如您所见,下拉菜单中没有任何显示。但是同时,所有数据都将显示在下面的列表中。

我尝试通过不带任何库的普通HTML选择来实现,目前正在使用react-select。我也尝试过这个:

{ posts? (<Select options={posts}) : null }

但是没有成功。我在这里想念什么?如何在下拉菜单中显示从服务器获取的数据?

2 个答案:

答案 0 :(得分:5)

您需要在getOptionLabel上添加一个Select道具。

Working Demo

<Select options={posts} getOptionLabel={item=>item}/>

From the Docs

getOptionLabel typeof getOptionLabel = (option) => string

将选项数据解析为字符串,以供组件显示为标签

答案 1 :(得分:1)

反应选择接受值和标签属性。更新您的字段或使用与 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>
  );
} 

工作Live demo