无法将项目添加到Material-UI表单

时间:2019-10-15 08:34:10

标签: reactjs forms material-ui

我从其他人那里获得了一个项目,我需要在用react和material-ui创建的表单中添加一些项目。我可以使文本字段正常工作,但是如果我尝试添加一个下拉列表,则在选择时它不保存该值。

我遵循与创建该表单的人所使用的表单相同的约定。

我添加了一个带有FormControl组件的网格项。还设置了默认道具,其中设置了一个“游戏”对象,该对象具有所有表单字段作为属性。我还在那里添加了新的字段项目。

这是整个表单的组成部分,因为我不确定问题的实际出处。

import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import history from '~/utils/history';
import { FormControl, Button, TextField, Grid, MenuItem, FormHelperText } from '@material-ui/core';
import { DateTimePicker } from 'material-ui-pickers';
import gameState from '~/utils/enums';
import { dateTime } from '~/utils/formats';

import { getById, create, update, remove } from '~/services/games';
import { getAll as getLeagues } from '~/services/leagues';
import { getAll as getSeasons } from '~/services/seasons';
import { getAll as getTeams } from '~/services/teams';

const GameForm = ({ game, id }) => {
  useEffect(() => {
    console.log({ form, game });
  });

  const [edit, setEdit] = useState(false);
  const [form, setForm] = useState(game);
  const [error, setError] = useState('');
  const [variant, setVariant] = useState('outlined');

  const [leagues, setLeagues] = useState([]);
  const [seasons, setSeasons] = useState([]);
  const [teams, setTeams] = useState([]);
  const [gametype, setGametype] = useState(1);

  const gametypes = [
    { key: 0, value: 'Series Game' },
    { key: 1, value: 'Playoff' },
    { key: 2, value: 'Final' },
    { key: 3, value: 'Else' }
  ];

  useEffect(() => {
    getSeasons()
      .then(({ data }) => {
        setSeasons(data);
        return getLeagues();
      })
      .then(({ data }) => {
        setLeagues(data);
        if (id) {
          getById(id).then(({ data }) => setForm(data));
        } else {
          setEdit(true);
        }
      });
  }, []);

  useEffect(() => {
    if (edit) {
      setVariant('outlined');
    } else {
      setVariant('standard');
    }
  }, [edit]);

  useEffect(() => {
    if (form.league) {
      getTeams({ leagues: [form.league] }).then(({ data }) => setTeams(data));
    }
  }, [form.league]);

  useEffect(() => {
    if (form.gametype) {
      setGametype('Playoff');
    }
  }, [form.gametype]);

  const handleChange = ({ target }) => {
    let { name, value } = target;
    setForm({
      ...form,
      [name]: value
    });
  };

  const handleDateChange = formInputName => {
    const dateHandler = moment => {
      setForm({
        ...form,
        [formInputName]: moment ? moment.toDate() : null
      });
    };
    return dateHandler;
  };

  const handleFormSubmit = () => {
    if (!edit) {
      setEdit(true);
    } else {
      new Promise(resolve => {
        resolve(form._id ? update(form) : create(form));
      })
        .then(() => {
          history.push('/games');
        })
        .catch(error => setError(error.response.data.error));
    }
  };
  const handleDelete = () => {
    if (window.confirm(`Delete permanently?`)) {
      remove(id).then(() => history.goBack());
    }
  };

  const handleCancel = () => {
    if (edit && id) {
      setEdit(false);
    } else {
      history.goBack();
    }
  };
  return (
    <Grid container spacing={8} justify="space-between">
      <Grid item xs={12} md={6}>
        <FormControl margin="normal" required fullWidth variant="outlined">
          <TextField
            required
            select
            id="season"
            name="season"
            label="Season"
            variant={variant}
            disabled={!edit}
            value={form.season}
            onChange={handleChange}
          >
            {seasons.map(option => (
              <MenuItem key={option.name} value={option._id}>
                {option.name}
              </MenuItem>
            ))}
          </TextField>
        </FormControl>
      </Grid>
      <Grid item xs={12} md={6}>
        <FormControl margin="normal" required fullWidth variant="outlined">
          <TextField
            required
            select
            id="league"
            name="league"
            label="League"
            variant={variant}
            disabled={!edit}
            value={form.league}
            onChange={handleChange}
          >
            {leagues.map(option => (
              <MenuItem key={option.name} value={option._id}>
                {option.name}
              </MenuItem>
            ))}
          </TextField>
        </FormControl>
      </Grid>
      <Grid item xs={12}>
        <FormControl margin="normal" required fullWidth variant="outlined">
          <DateTimePicker
            required
            id="start"
            name="start"
            label="Game starts"
            variant={variant}
            disabled={!edit || !form.season}
            autoOk
            ampm={false}
            keyboard
            clearable
            minDate={form.season ? seasons.find(({ _id }) => _id === form.season).start : undefined}
            minDateMessage="Cannot start before the season begins"
            maxDate={form.season ? seasons.find(({ _id }) => _id === form.season).end : undefined}
            maxDateMessage="Cannot start after the end of the season"
            value={form.start}
            onChange={handleDateChange('start')}
            {...dateTime}
          />
          <FormHelperText disabled={!form.season}>
            {!form.season ? 'Select season first' : undefined}
          </FormHelperText>
        </FormControl>
      </Grid>
      <Grid item xs={12} md={6}>
        <FormControl margin="normal" required fullWidth variant="outlined">
          <TextField
            required
            select
            id="home"
            name="home"
            label="Home team"
            variant={variant}
            disabled={!edit || !form.league}
            helperText={!form.league ? 'Select league first' : undefined}
            value={form.home}
            onChange={handleChange}
          >
            <MenuItem value="">
              <em>None</em>
            </MenuItem>
            {teams
              .filter(({ _id }) => _id !== form.away)
              .map(option => (
                <MenuItem key={option.name} value={option._id}>
                  {option.name}
                </MenuItem>
              ))}
          </TextField>
        </FormControl>
      </Grid>
      <Grid item xs={12} md={6}>
        <FormControl margin="normal" required fullWidth variant="outlined">
          <TextField
            required
            select
            id="away"
            name="away"
            label="Team away"
            variant={variant}
            disabled={!edit || !form.league}
            helperText={!form.league ? 'Select league first' : undefined}
            value={form.away}
            onChange={handleChange}
          >
            <MenuItem value="">
              <em>None</em>
            </MenuItem>
            {teams
              .filter(({ _id }) => _id !== form.home)
              .map(option => (
                <MenuItem key={option.name} value={option._id}>
                  {option.name}
                </MenuItem>
              ))}
          </TextField>
        </FormControl>
      </Grid>
      <Grid item xs={12} md={6}>
        <FormControl margin="normal" required fullWidth variant="outlined">
          <TextField
            required
            select
            id="gametype"
            label=" Game type"
            variant={variant}
            disabled={!edit}
            value={form.gametype}
            onChange={handleChange}
          >
            <MenuItem value="">
              <em>None</em>
            </MenuItem>
            {gametypes.map(option => (
              <MenuItem key={option.key} value={option.value}>
                {option.value}
              </MenuItem>
            ))}
          </TextField>
        </FormControl>
      </Grid>
      <Grid item xs={12} md={6}>
        <FormControl margin="normal" required fullWidth variant="outlined">
          <TextField
            text
            id="umpire"
            label="Umpire"
            variant={variant}
            disabled={!edit || !form.league}
          />
        </FormControl>
      </Grid>
      <Grid item xs={12} md={6}>
        <FormControl margin="normal" required fullWidth variant="outlined">
          <TextField
            text
            id="scorekeeper"
            label="Scorekeeper"
            variant={variant}
            disabled={!edit || !form.league}
          />
        </FormControl>
      </Grid>
      <Grid item xs={12} md={6}>
        <FormControl margin="normal" required fullWidth variant="outlined">
          <TextField
            text
            id="referee1"
            label="Referee 1"
            variant={variant}
            disabled={!edit || !form.league}
          />
        </FormControl>
      </Grid>
      <Grid item xs={12} md={6}>
        <FormControl margin="normal" required fullWidth variant="outlined">
          <TextField
            text
            id="referee2"
            label="Referee 2"
            variant={variant}
            disabled={!edit || !form.league}
          />
        </FormControl>
      </Grid>
      <Grid item xs={12} md={6}>
        <FormControl margin="normal" required fullWidth variant="outlined">
          <TextField
            text
            id="referee3"
            label="Referee 3"
            variant={variant}
            disabled={!edit || !form.league}
          />
        </FormControl>
      </Grid>
      <Grid item xs={edit && id ? 4 : 6}>
        <Button variant="outlined" color="secondary" fullWidth onClick={handleCancel}>
          {edit && id ? 'Cancel' : 'Back'}
        </Button>
      </Grid>
      {edit && id ? (
        <Grid item xs={4}>
          <Button
            type="submit"
            variant="contained"
            color="secondary"
            fullWidth
            onClick={handleDelete}
          >
            Delete
          </Button>
        </Grid>
      ) : null}
      <Grid item xs={edit && id ? 4 : 6}>
        <Button
          type="submit"
          variant="outlined"
          color="primary"
          fullWidth
          onClick={handleFormSubmit}
        >
          {edit ? (id ? 'Save' : 'Create') : 'Edit Game'}
        </Button>
      </Grid>
      {!edit ? (
        <Grid item xs={12}>
          <Button
            variant="outlined"
            color="primary"
            fullWidth
            onClick={() => {
              history.push('/games/' + id + '/scores');
            }}
          >
            EDIT SCORES
          </Button>
        </Grid>
      ) : null}
    </Grid>
  );
};

GameForm.defaultProps = {
  game: {
    season: '',
    league: '',
    start: null,
    home: '',
    away: '',
    gametype: '',
    umpire: '',
    scorekeeper: '',
    referee1: '',
    referee2: '',
    referee3: ''
  }
};

GameForm.propTypes = {
  //classes: PropTypes.object.isRequired,
  game: PropTypes.object
};

export default GameForm;

我注意到,如果我将游戏对象打印到控制台,它只会显示旧的表单项,而不显示我添加的新表单项。新项目包括:游戏类型,裁判,记分员,裁判1-3。

我已经尝试使这项工作进行了几天,所以我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

其中您需要onChange = {handleChange},还需要提供名称作为道具

顺便说一句,我强烈建议您将这些useStates组合为一个状态对象

例如,另一种方法禁止在组件中进行多次useState()调用。您将状态保持在一个对象中。

function Form() {
  const [state, setState] = useState({
    edit: '',
    form: '',
    error: '',
  });
  // ...
}

需要明确的是,挂钩确实允许这种样式。您不必将状态拆分为一堆状态变量(请参见doc)。