【问题标题】:React dropdown fetch from API从 API 获取 React 下拉列表
【发布时间】:2020-10-07 16:47:32
【问题描述】:

我想构建“React Dropdown”,它会在我输入用户姓名的首字母时为我提供选择用户的选项。

用户数据来自我的后端 API,采用 JSON 格式。

// http://localhost:5000/users
{
  "users": [
    {
      "company_id": 1,
      "name": "Sally Mae"
    },
    {
      "company_id": 2,
      "name": "Johnathan Ives"
    },
    {
      "company_id": 3,
      "name": "John Smith"
    }
  ]
}

这是我的获取部分,但我无法获取,但我的服务器正在运行,这是代码


fetchData = (inputValue, callback) => {
    if (!inputValue) {
      callback([]);
    } else {
        setTimeout(() => {
  fetch("http://127.0.0.1:5000/users/" + inputValue, {
    method: "GET",
  })
  .then((resp) => {
    console.log(resp);
    return resp.json()
  }) 
  .then((data) => {
     const tempArray = [];
     data.forEach((users) => {
      console.log(tempArray);
      tempArray.push({ label: `${users.name}`, value: `${users.name}`});
      console.log(tempArray);
     });
     callback(tempArray);            
  })
  .catch((error) => {
    console.log(error, "catch the hoop")
  });
});
}
}


感谢任何帮助!

【问题讨论】:

  • 你好!请查看帮助中心 - 特别是主题How do I ask a good question? 该问题目前需要一些额外的细节,例如,您遇到了什么错误?应该发生什么以及正在发生什么?你试过什么?请使用您问题下方的edit 按钮为您的问题添加详细信息。

标签: reactjs api fetch dropdown react-select


【解决方案1】:

我认为您在这里误解的是您的 loadOptions 属性中的 callback 是您包装检索方法的位置。

const getData = (inputValue) =>
  fetch('http://127.0.0.1:5000/users/' + inputValue, {
    method: 'GET',
  })
    .then((resp) => resp.json())
    .then((data) =>
      data.map((user) => ({ label: user.name, value: user.name }))
    )
    .catch((error) => {
      console.log(error, 'catch the hoop');
    });

const fetchData = (inputValue, callback) => {
  if (!inputValue) {
    callback(Promise.resolve([]));
  } else {
    callback(getData(inputValue));
  }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2012-05-04
    • 2022-08-03
    • 1970-01-01
    • 2014-06-19
    • 2021-10-13
    相关资源
    最近更新 更多