Как заполнить поле со списком задач в форме обслуживания - PullRequest
0 голосов
/ 10 ноября 2019

Я хочу заполнить поле со списком задачами, но когда я делаю, страница становится пустой, нажмите на comboBox.

Это моя модель сервиса:

 const mongoose = require('mongoose');
 const { Schema } = mongoose;
 const serviceSchema = new Schema({
  name: String,
  description: String,
  pricePerHour: Number,
  relatedTodos: 
    [{type: mongoose.Schema.Types.ObjectId, 
  ref:'todos'}],
  createdAt: Date,
  UpdatedAt: Date
 });

 mongoose.model('services', serviceSchema);

Это моя задачамодель:

const mongoose = require('mongoose');
const { Schema } = mongoose;

    const todoSchema = new Schema({
   name: String,
   description: String,
   isDone: Boolean,
   createdAt: Date,
   updatedAt: Date
  });

 mongoose.model('todos', todoSchema);

ActionsTodos.js:

import axios from 'axios';
import { typesTodos } from './types';

export const listTodos = () => async dispatch => {
 const res = await axios.get('/api/todos');
  dispatch({type: typesTodos.LIST_TODOS, payload: res.data});
 }

ReducerTodos.js:

import { typesTodos} from '../actions/types';

const INITIAL_STATE = {
  listTodos: [],
  todo: {},
  loading: false,
  errors: {}
 };

 export default function(state = INITIAL_STATE, action) {
   switch (action.type) {

 case typesTodos.LIST_TODOS :
        return{
          ...state,
           listTodos: action.payload
         };

     default:
       return state;
   }
 }

ReducerIndex.js:

import { combineReducers } from 'redux';
import { reducer as reduxForm } from 'redux-form';
import reducerTodos from './ReducerTodos';
import reducerServices from './ReducerServices';

export default combineReducers({
  form: reduxForm,
  listTodos: reducerTodos,
  servicesDs: reducerServices,
  });

И наконец, ServiceForm.jsx:

 import React, { Component } from 'react';
 import { reduxForm, Field,FieldArray} from 'redux-form';
 import { Link } from 'react-router-dom';
 import {listTodos} from '../../actions/ActionsTodos';
 import { connect } from 'react-redux';
 import ComboBox from 'react-widgets/lib/Combobox';
 import moment from 'moment';
 import momentLocaliser from 'react-widgets-moment-localizer';
 import 'react-widgets/dist/css/react-widgets.css';

 momentLocaliser(moment)


class ServiceForm extends Component {
   componentWillReceiveProps = nextProps => {
     // Load Contact Asynchronously
     const { service } = nextProps;
     if (service._id !== this.props.service._id) {
       // Initialize form only once
      this.props.initialize(service);
       this.isUpdating = true;
     }
   };

   renderField = ({ input, label, type, meta: { touched, error } }) => (
     <div className='form-group'>
      <label forname={input.name}>{label}</label>
      <input
        {...input}
        type={type}
        className='form-control'
        id={input.name}
        placeholder={input.label}
     />
      <div className='text-danger' style={{ marginBottom: '20px' }}>
        {touched && error}
      </div>
     </div>
  );

renderComboBox = ({ input, data, valueField, textField }) =>

<ComboBox {...input}
data={data}
valueField={valueField}
textField={textField}
onChange={input.onChange}
/> 


componentDidMount(){
  this.props.listTodos();
}


    renderArrayTodos = ({ fields, meta: { error,submitFailed } }) => (
      <ul>
        <li>
          <button type="button" onClick={() => fields.push()}>Add todo</button>
          {submitFailed && error && <span>{error}</span>}
         </li>
        {fields.map((todos, index) =>
          <li key={index}>
            <button
              type="button"
              title="Remove Todo"
              onClick={() => fields.remove(index)}/>

        <div>
           <label>todo</label>
         <Field
        name="relatedTodos"
         type='ComboBox'
        data={this.searchTodos}
        valueField="value"
        textField="todo"
        component={this.renderComboBox}
       />
       </div>
          </li>

        )}

        {error && <li className="error">{error}</li>}
      </ul>
    );
       searchTodos = () =>{
      return this.props.listTodos.map((todo)=>{

        return(
          <div>
            <ul>
              <li>id: {todo._id}</li>
              <li>name: {todo.name}</li>
              <li>description: {todo.description}</li>
              <li>isDone: {todo.isDone}</li>
            </ul>

           </div>
        )
     });


     ArrayFieldTodos = props => {
     const { handleSubmit, pristine, reset, submitting } = props
       return(
        <form onSubmit={handleSubmit}>
         <FieldArray name="relatedTodos" component={this.renderArrayTodos} />
           <div>
             <button type="submit" disabled={submitting}>
              Submit
            </button>
        <button type="button" disabled={pristine || submitting} onClick={reset}>
          Clean Values
        </button>    
      </div>
        </form>
      )
     }

  render() {
    const { handleSubmit, loading} = this.props;

    if (loading) {
      return <span>Loading...</span>;
    }
    return (
      <form onSubmit={handleSubmit}>
        <Field
          name='name
          type='text'
          component={this.renderField}
          label='Name'
        />
        <Field
          name='description'
          type='text'
          component={this.renderField}
          label='Description'
        />
         <Field
          name='pricePerHour'
          type='text'
          component={this.renderField}
          label='PricePerHour'
        />
             <FieldArray
             name = 'relatedTodos'
             component ={this.ArrayFieldTodos}
             label = 'RelatedTodos'
             />
        <div>
      </div>



            <Link className='btn btn-light mr-2' to='/services'>
          Cancel
        </Link>
        <button className='btn btn-primary mr-2' type='submit'>
          {this.isUpdating ? 'Update' : 'Create'}
        </button>
      </form>
    );
  }
}
    function mapStateToProps(state){
     return{
    listTodos: state.listTodos.listTodos
      }
    }
    ServiceForm = connect(mapStateToProps,{listTodos})(ServiceForm);

    export default reduxForm({form:'service')(ServiceForm);

Я нажимаю на сервисы. Услуги заряжают меня хорошо. Затем я делаю клик по новой. Я вижу кнопку Добавить todo. И я нажимаю на него, и он открывает поле со списком. Но когда я нажимаю на ComboBox, страница становится пустой.

Что не так? Ошибка может быть в searchTodos.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...