使用 Axios 进行动态 React 选择

问题描述 投票:0回答:3

我刚刚开始向我的 Ruby on Rails 前端添加一些 React。

我有两个数据模型,称为

coffee_beans
countries

我想在

coffee_beans
的表单上添加一个选择下拉列表,用于拉入国家/地区,包括
id
country_name
字段。我需要将 id 提交到
coffee_beans
表。

我可以通过 axios 很好地检索数据,但我很难让数据显示在我的下拉列表中。

我正在使用 React-Select。

import React from 'react';
import axios from 'axios';
import Select from 'react-select';

class Country extends React.Component {
    constructor() {
        super();
  }

  componentDidMount() {
    axios.get(`/countries.json`)
      .then(res => {
        const countries = res.data;
        this.setState({ countries });
      })
  }

  render() {
    let optionItems = countries.map(countries => 
        <option key={countries.id}>{countries.country_name}</option>
    );

    return (
        <div className="">
        <label htmlFor="coffee_beans_countries">Country</label>
            <Select id="country" name="coffee_beans[countries]" options={optionItems} />
        </div>
    )
  }
}

export default Country

渲染元素

import React from 'react'
import ReactDOM from 'react-dom'
import Country from 'Country'

document.addEventListener('turbolinks:load', function() {
    var element = document.getElementById("country-component");
    ReactDOM.render(<Country />, element);
});

更新 我现在有以下代码,但收到错误:

warning.js:33 警告:只能更新已安装或正在安装的 成分。这通常意味着您调用了 setState、replaceState 或 对已卸载的组件强制更新。这是禁止操作。

import React from 'react';
import axios from 'axios';
import Select from 'react-select';

class Country extends React.Component {
    state = {
        countries: []
      }

  componentDidMount() {
    axios.get(`/countries.json`)
      .then(res => {
        const countries = [];
        this.setState({ countries });
      });
      console.log(countries)
  }

  render() {
    let optionItems = this.state.countries.map(countries => 
        <option key={countries.id}>{countries.country_name}</option>
    );

    return (
        <div className="">
        <label htmlFor="coffee_beans_countries">Country</label>
            <Select id="country" name="coffee_beans[countries]" options={optionItems} />
        </div>
    )
  }
}

export default Country
reactjs drop-down-menu axios react-select
3个回答
0
投票

let optionItems = countries.map

应该是

let optionItems = this.state.countries

还需要设置一个初始状态。所以:

import React from 'react';
import { render } from 'react-dom';
import Select from 'react-select';

class Country extends React.Component {
  state = {
    countries: []
  }

  componentDidMount() {
    const countries = []
    this.setState({ countries });
  }

  render() {
    let optionItems = this.state.countries.map(countries =>
      <option key={countries.id}>{countries.country_name}</option>
    );

    return (
      <div className="">
        <label htmlFor="coffee_beans_countries">Country</label>
        <Select id="country" name="coffee_beans[countries]" options={optionItems} />
      </div>
    )
  }
}

render(<Country />, document.getElementById('root'));

实例这里


0
投票

由于国家是国家中唯一的东西,请尝试

this.state.map(countries => ...
-或者- 在组件DidMount中,
this.setState({countries: countries})


0
投票

对于更新的警告:几天前我遇到了同样的问题,但我使用的是 fetch api,所以我不知道它是否会起作用。我刚刚将我的 componentDidMount() 设为异步,并在我在其中调用的每个异步方法之前放置一个等待。 这是最终结果:

async componentDidMount() {
    await this._getUserData();
}

_getUserData = async () => {
    try {

        const response = await fetch(url);
        this.setState({firstAccess: responseJson.data.name});

    } catch(error) {
        console.log(error);
    }
}

我对 React 和 JavaScript 很陌生,所以我不确定它为什么起作用,但 React 似乎只是想警告你,当组件尚未安装时,可以调用 Promise 中的 setState() ,这如果您在 axios 调用下面调用另一个 setState ,导致组件重新渲染(不知道这是否被视为如警告所述那样被卸载),并且有一个更改,承诺 setState 将在那里被调用,则会发生这种情况。如果你让 componentDidMount 异步,它允许你等待 Promise 被解决,这样你就不会遇到问题了。但再说一遍...我不确定哈哈。

© www.soinside.com 2019 - 2024. All rights reserved.