Получить данные из базы данных с помощью `axios`` get` при использовании `act-select` в ReactJs Laravel - PullRequest
0 голосов
/ 08 мая 2019

Я пытаюсь получить select option из моей базы данных.Я использую реагировать-выберите , я уже тестировал этот код и работает нормально.Но я столкнулся с проблемой при попытке получить данные из базы данных.Я пробовал что-то вроде ниже, но получаю эту ошибку - TypeError: Cannot read property 'data' of undefined в console.log(response.data), показывая данные в консоли правильно, как в примере, приведенном JedWatson.Но эти данные не отображаются в <Select options={options}/>.Я представил весь мой код ниже, кто-нибудь поможет мне решить эту проблему?

import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
import Select from 'react-select';

const axios = require('axios');
const axios = require('axios');
// const options = [
//   { value: 1, label: 'Chocolate' },
//   { value: 2, label: 'Bread' },
// ];
// console.log(options);
const options = [
      axios.get('/api/active-categories')
        .then(function (response) {
             // console.log(response.data);
             return response[0].data;
         })
        .catch(function (error) {
            // handle error
            console.log(error);
         })
];
class CreateNewProduct extends Component { 

  constructor(props) {
    super(props);
    this.state = {
      selectedOption: [],
      newProduct: {
        name: '',
        description: '',
        product_categories: [],
       },
     };
    this.handleChange = this.handleChange.bind(this);
    this.handleInput = this.handleInput.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange(selectedOption){
      this.setState({ selectedOption });
  }
  handleInput(key, e){
    let state = Object.assign({}, this.state.newProduct);
    state[key] = e.target.value;
    this.setState({newProduct: state});
  }
  handleSubmit(e){
    e.preventDefault();
    const product = {
      name: this.state.newProduct.name,
      description: this.state.newProduct.description,
      product_categories: this.state.selectedOption.value,
    }
    axios.post('/api/save-new-product', product).then((response) => {
    }).catch(err => {});
}
render() {
   const { selectedOption } = this.state;
   return (
     <React.Fragment>
      <div className="container-fluid">
        <form className="uk-form-stacked" onSubmit={this.handleSubmit}>
          <div className="uk-margin">
            <label className="uk-form-label" htmlFor="form-stacked-text">Categories <span className="required-span">*</span></label>
               <Select
                  value={selectedOption}
                  onChange={this.handleChange}
                  options={options}
                  isMulti
                />
           </div>
           <div className="footer">
              <button type="submit" className="uk-button uk-button-primary uk-button-small float-right">Save</button>
           </div>
        </form>
      </div>
     </React.Fragment>
    );
  }
}

От моего controller -

public function activeCategories()
{
   return $categories = Category::where('status', 1)->get(['id AS value', 'name AS label']);
}
...