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

Я пытаюсь получить доступ из формы избыточности, которая заполняется внутри моего редуктора, чтобы я мог заменить значения другого объекта в массив. Как вы правильно отправляете и передаете значения из избыточной формы?

Я попытался передать ее обратно через действия избыточности. Я попытался получить доступ к нему в редукторе прямо из магазина, потому что я решил, что именно там он хранится. Я чувствую, что делаю что-то не так

class EditWorkoutItem extends Component {
  state = {
    open: false
  };

  // Opens the page
  handleClickOpen = () => {
    this.props.loadData(this.props.id);
    this.setState({ open: true });
  };

  // Cancels the changes and closes the page
  handleClose = () => {
    this.setState({ open: false });
  };

  // Passes back the id to the parent so the correct item can be replaced.
  // Passes back the new workout list
  handleSubmitChanges = e => {
    e.preventDefault();
    this.props.editWorkout(this.props.id); // this passes the workouts id back
    this.setState({ open: false });
  };

  render() {
    return (
      <>
        <Button
          color="primary"
          size="small"
          disableRipple
          onClick={this.handleClickOpen}
        >
          edit
        </Button>
        <Dialog
          open={this.state.open}
          onClose={this.handleClose}
          style={styles.dialog}
          fullScreen
        >
          <DialogTitle>Edit This Workout</DialogTitle>
          <form onSubmit={this.props.handleSubmit} style={styles.form}>
            <DialogContent>
              <Field
                name="date"
                component={DatePicker}
                format={null}
                hintText="Date Of Workout"
                fullWidth={true}
                locale="en-US"
              />
              <Field
                name="name"
                component={TextField}
                floatingLabelText="Workout Name"
                style={styles.textfield}
              />
              <Field
                name="duration"
                type="number"
                component={TextField}
                floatingLabelText="Estimated Duration"
                style={styles.textfield}
              />
              <FieldArray name="exercises" component={renderExercises} />
            </DialogContent>
            <DialogActions>
              <Button
                color="primary"
                type="submit"
                onClick={this.handleSubmitChanges} //Submitted here
              >
                Submit Changes
              </Button>
              <Button onClick={this.handleClose}>Cancel</Button>
            </DialogActions>
          </form>
        </Dialog>
      </>
    );
  }
}

Это редуктор:

    case "EDIT_WORKOUT":
      return (state = {
        ...state,
        workoutlist: state.workoutlist.map(workout => {
          // Find the item with the matching id
          if (workout.id === action.payload.id) {
            // Return a new object
            return {
              ...workout, // copy the existing item
              workout: action.values // replace the current workout
            };
          }
          // Leave every other item unchanged
          return workout;
        })
      });

Независимо от того, что я делаю, значения не доходят до редуктора. Любая помощь будет принята с благодарностью !!!

1 Ответ

0 голосов
/ 21 октября 2019

Вы когда-нибудь пытались использовать mapDistchpathToProps для отправки действий в классе EditWorkoutItem следующим образом:

const connectToRedux = connect(null, 
   dispatch => ({
       handleSubmitChanges: values => {
           // values here is all value of your form
           console.log(values);
           dispatch({ type: "EDIT_WORKOUT", payload: values }) // dispatch an action with
           // type is EDIT_WORKOUT and payload is all value of Redux-form
       }
   })
)

Звоните handleSubmitChanges в форме:

<form onSubmit={this.props.handleSubmitChanges} style={styles.form}>
...
...
<Button
   color="primary"
   type="submit"
   // onClick={this.handleSubmitChanges} // remove this
>

Теперь,в редукторе вы можете получить данные в действии от создателя действия с типом EDIT_WORKOUT:

case "EDIT_WORKOUT":
   console.log(action.payload) // You can receive values of Redux-form here
   return;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...