简体   繁体   English

React JS-我很难在项目的Select框中从API获取JSON信息

[英]React JS - I'm having difficult to get JSON informations from API on a Select box in my project

I'm new to React and JSON stuff, so I'm having some trouble to get JSON information and put it on an Option tag inside the Select on my project. 我是React和JSON的新手,因此在获取JSON信息并将其放在我项目的Select内的Option标签上时遇到了一些麻烦。 What am I doing wrong? 我究竟做错了什么?

Here's my code: 这是我的代码:

    componentWillMount() {
        this.fetchData();
      }

      fetchData() {
        fetch("https://grupoprever-api.qap/listas/estados", { mode: "cors" })
          .then(response => response.json())
          .then(parsedJSON => {
            parsedJSON.map(estado => ({
              v: `${estado.key}`,
              d: `${estado.value}`
            }));
          })

          .then(estados =>
            this.setState({
              estados
            })
          )

          .catch(error => console.log("Erro no Fetch:", error));
      }

And I'm trying to put this information in here: 我正在尝试将此信息放在这里:

    <div className="meioCampo">
              <span>Estado:</span>
              <select
                id="estadosDropdown"
                onChange={e => this.setState({ escolhidoEstado: e.target.value })}
              >
                {this.state.estados.map(estado => {
                  return (
                    <option key={estado.v} value={estado.v}>
                      {estado.d}
                    </option>
                  );
                })}
              </select>
            </div>

All of this are inside a Component. 所有这些都在组件内部。

Oh, my JSON data is like this: 哦,我的JSON数据是这样的:

{

    "AC":"Acre",
    "AL":"Alagoas",
    "AM":"Amaz\u00f4nia"

}

You're not returning any data from a map function. 您不会从map函数返回任何数据。

change 更改

.then(parsedJSON => {
    parsedJSON.map(estado => ({
      v: `${estado.key}`,
      d: `${estado.value}`
    }));
 })

to

.then(parsedJSON => {
    return parsedJSON.map(estado => ({
      v: `${estado.key}`,
      d: `${estado.value}`
    }));
  })

EDIT: 编辑:

Also please don't call your api from componentWillMount method. 另外,请不要从componentWillMount方法调用您的api。 While your code might be working, this lifecycle method is already marked as UNSAFE and should be avoided. 当您的代码可能正在工作时,此生命周期方法已被标记为UNSAFE,应避免使用。 Call your fetch request from componentDidMount instead. 而是从componentDidMount调用获取请求。 Initialize default state of your Component like: 初始化组件的默认状态,例如:

constructor(props) {
  super(props);
  ... // your other code in constructor

  this.state = {
     estados: null,
     // add other state variables here...
  }
}

and add a check for 'null' state to your render() method like so: 并在render()方法中添加对“ null”状态的检查,如下所示:

<div className="meioCampo">
  <span>Estado:</span>
  <select
    id="estadosDropdown"
    onChange={e => this.setState({ escolhidoEstado: e.target.value })}         >
      {this.state.estados && this.state.estados.map(estado => {
        return (
          <option key={estado.v} value={estado.v}>
            {estado.d}
          </option>
        );
      })}
 </select>
</div>

EDIT 2: 编辑2:

as your response body is an object (not list), then you can try to following code: 由于您的响应主体是一个对象(不是列表),因此您可以尝试执行以下代码:

fetchData() {
  fetch("https://grupoprever-api.qap/listas/estados", { mode: "cors" })
    .then(response => response.json())
    .then(estados =>
       this.setState({
          estados
      })
    );

then generate your options list with Object.keys() method: 然后使用Object.keys()方法生成您的选项列表:

render() {
   ....
  const {estados} = this.state;

  return(
    <div className="meioCampo">
      <span>Estado:</span>
      <select
        id="estadosDropdown"
        onChange={e => this.setState({ escolhidoEstado: e.target.value })}         >
          {estados && Object.keys(estados).map(key => {
            return (
              <option key={key} value={key}>
                {estados[key]}
              </option>
            );
          })}
     </select>
    </div>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM