Как я могу установить флажок в React, если данные в другом массиве верны - PullRequest
0 голосов
/ 09 мая 2020

как установить флажок, если данные в другом массиве равны его значению? Эти флажки добавляют значение массиву, их всего три, и люди могут выбирать от одного до трех из вариантов, и они загружаются в поле «Компании», а затем сохраняются в его профиле. Это сделано, проблема в том, что когда я перезагружаю форму, чтобы отредактировать ее снова, у меня есть значения во вводе «компании», но флажок установлен по умолчанию, поэтому, если я снова щелкну поле, оно повторяет это значение и не должно Не больше трех.

Надеюсь, я правильно объяснил, ниже lo go и снимок экрана.

Так я выполняю загрузку во входных данных.

const onClick = (e) => {
    let index;

    if (e.target.checked) {
      profile.companies.push(e.target.value);
    } else {
      index = profile.companies.indexOf(e.target.value);
      profile.companies.splice(index, 1);
    }

    // sort the array
    const companies = profile.companies.sort();
  };

Это код ES6

<div className='account-type col-xl-4'>
            <input
              id='at'
              className='account-type-radio'
              type='checkbox'
              name='select3'
              value='Airpath Testing Services'
              onClick={(e) => onClick(e)}
              onChange={(e) => onChange(e)}
            />
            <label htmlFor='at' className='ripple-effect-dark'>
              Airpath Testing Services
            </label>
          </div>

Это полный код. Я работал с контекстом и хуками.

import React, { useState, useEffect, useContext } from 'react';
import { withRouter } from 'react-router-dom';

// Contexts
import AlertContext from '../../context/alert/alertContext';
import LogContext from '../../context/log/logContext';
import ProfileContext from '../../context/profile/profileContext';

const EditProfile = ({ history }) => {
  const logContext = useContext(LogContext);
  const profileContext = useContext(ProfileContext);
  const alertContext = useContext(AlertContext);

  const { setAlert } = alertContext;
  const { getCurrentProfile, createProfile, profile, loading } = profileContext;
  const { setLog } = logContext;

  const [formData, setFormData] = useState({
    companies: '',
    title: '',
    bio: '',
    skills: '',
    certifications: '',
    linkedin: '',
    twitter: '',
    slack: '',
    behance: '',
  });

  const onClick = (e) => {
    let index;

    if (e.target.checked) {
      profile.companies.push(e.target.value);
    } else {
      index = profile.companies.indexOf(e.target.value);
      profile.companies.splice(index, 1);
    }

    // sort the array
    const companies = profile.companies.sort();
  };

  useEffect(() => {
    getCurrentProfile();

    setFormData({
      companies:
        (profile && loading) || !profile.companies
          ? ''
          : profile.companies.join(', '),
      title: (profile && loading) || !profile.title ? '' : profile.title,
      bio: (profile && loading) || !profile.bio ? '' : profile.bio,
      skills:
        (profile && loading) || !profile.skills
          ? ''
          : profile.skills.join(', '),
      certifications:
        (profile && loading) || !profile.certifications
          ? ''
          : profile.certifications.join(', '),
      linkedin:
        (profile && loading) || !profile.social ? '' : profile.social.linkedin,
      twitter:
        (profile && loading) || !profile.social ? '' : profile.social.twitter,
      slack:
        (profile && loading) || !profile.social ? '' : profile.social.slack,
      behance:
        (profile && loading) || !profile.social ? '' : profile.social.behance,
    });
  }, []);

  const {
    companies,
    title,
    bio,
    skills,
    certifications,
    linkedin,
    twitter,
    slack,
    behance,
  } = formData;

  const onChange = (e) => {
    if (profile && profile.companies.includes('Engineering')) {
      console.log('got it');
    }
    setFormData({
      ...formData,
      companies: profile.companies,
      [e.target.name]: e.target.value,
    });
  };

  const onSubmit = (e) => {
    e.preventDefault();
    setAlert('Your profile has been updated', 'success');
    setLog({ msg: 'Profile has been updated', type: 'success' });
    createProfile(formData, history, true);
  };

  return (
    <form onSubmit={(e) => onSubmit(e)}>
      <div className='content'>
        <div className='row'>
          <div className='submit-field'>
            <h5>Choose all that apply</h5>
          </div>
          <div className='account-type col-xl-4'>
            <input
              id='ag'
              className='account-type-radio'
              type='checkbox'
              name='select1'
              value='Airpath Group'
              onClick={(e) => onClick(e)}
              onChange={(e) => onChange(e)}
            />
            <label htmlFor='ag' className='ripple-effect-dark'>
              Airpath Group
            </label>
          </div>

          <div className='account-type col-xl-4'>
            <input
              id='ae'
              className='account-type-radio'
              type='checkbox'
              name='select2'
              value='Airpath Engineering'
              onClick={(e) => onClick(e)}
              onChange={(e) => onChange(e)}
            />
            <label htmlFor='ae' className='ripple-effect-dark'>
              Airpath Engineering
            </label>
          </div>

          <div className='account-type col-xl-4'>
            <input
              id='at'
              className='account-type-radio'
              type='checkbox'
              name='select3'
              value='Airpath Testing Services'
              onClick={(e) => onClick(e)}
              onChange={(e) => onChange(e)}
            />
            <label htmlFor='at' className='ripple-effect-dark'>
              Airpath Testing Services
            </label>
          </div>
        </div>

        <div className='row'>
          <div className='col-xl-12'>
            <div className='submit-field'>
              <div className='row'>
                <div className='account-type col-xl-6'>
                  <div className='sidebar-widget'>
                    <h3>Companies</h3>
                    <small>Change this field with buttons above</small>
                    <input
                      type='text'
                      name='companies'
                      value={companies}
                      onChange={(e) => onChange(e)}
                      disabled
                    />
                  </div>
                </div>

                <div className='col-xl-6'>
                  <div className='submit-field'>
                    <h5>Title</h5>
                    <small>e.g. CEO or CFO</small>
                    <input
                      name='title'
                      type='text'
                      className='with-border'
                      value={title}
                      onChange={(e) => onChange(e)}
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div className='row'>
          <div className='col-xl-6'>
            <div className='submit-field'>
              <h5>Skills</h5>
              <small>Add skills separated by comma</small>
              <input
                name='skills'
                type='text'
                className='with-border'
                value={skills}
                onChange={(e) => onChange(e)}
              />
              <div
                className='keywords-list'
                style={{ height: '100%', marginBottom: 20 }}
              >
                {profile &&
                  profile.skills.slice(0, 7).map((skill, index) => (
                    <span key={index} className='keyword'>
                      <span
                        className='keyword-text'
                        style={{ paddingLeft: 15 }}
                      >
                        {skill}
                      </span>
                    </span>
                  ))}
              </div>
            </div>
          </div>

          <div className='col-xl-6'>
            <div className='submit-field'>
              <h5>Certifications</h5>
              <small>Add skills separated by comma</small>
              <input
                name='certifications'
                type='text'
                className='with-border'
                value={certifications}
                onChange={(e) => onChange(e)}
              />
              <div
                className='keywords-list'
                style={{ height: '100%', marginBottom: 20 }}
              >
                {profile &&
                  profile.certifications
                    .slice(0, 7)
                    .map((certification, index) => (
                      <span key={index} className='keyword'>
                        <span
                          className='keyword-text'
                          style={{ paddingLeft: 15 }}
                        >
                          {certification}
                        </span>
                      </span>
                    ))}
              </div>
            </div>
          </div>
        </div>
        <div className='row'>
          <div className='col-xl-12'>
            <div className='submit-field'>
              <h5>Write your bio, remember this is public</h5>
              <textarea
                name='bio'
                value={bio}
                cols='30'
                rows='5'
                className='with-border'
                onChange={(e) => onChange(e)}
              ></textarea>
            </div>
          </div>
        </div>
        <div className='row'>
          <div className='col-xl-6'>
            <div className='submit-field'>
              <h5>LinkedIn</h5>
              <div className='input-with-icon'>
                <input
                  type='text'
                  name='linkedin'
                  className='with-border'
                  value={linkedin || ' '}
                  onChange={(e) => onChange(e)}
                />
                <i className='icon-brand-linkedin'></i>
              </div>
            </div>
          </div>
          <div className='col-xl-6'>
            <div className='submit-field'>
              <h5>Twitter</h5>
              <div className='input-with-icon'>
                <input
                  type='text'
                  name='twitter'
                  className='with-border'
                  value={twitter || ' '}
                  onChange={(e) => onChange(e)}
                />
                <i className='icon-brand-twitter'></i>
              </div>
            </div>
          </div>
          <div className='col-xl-6'>
            <div className='submit-field'>
              <h5>Slack</h5>
              <div className='input-with-icon'>
                <input
                  type='text'
                  name='slack'
                  className='with-border'
                  value={slack || ' '}
                  onChange={(e) => onChange(e)}
                />
                <i className='icon-brand-slack'></i>
              </div>
            </div>
          </div>
          <div className='col-xl-6'>
            <div className='submit-field'>
              <h5>Behance</h5>
              <div className='input-with-icon'>
                <input
                  type='text'
                  name='behance'
                  className='with-border'
                  value={behance || ' '}
                  onChange={(e) => onChange(e)}
                />
                <i className='icon-brand-behance'></i>
              </div>
            </div>
          </div>
        </div>

        <div className='col-xl-12'>
          <button
            type='submit'
            className='button ripple-effect big margin-top-30'
          >
            Save Changes
          </button>
        </div>
      </div>
    </form>
  );
};

export default withRouter(EditProfile);

Form screenshot

...