首页 > 解决方案 > 使用 react/redux 编辑表单时如何在输入中显示当前值

问题描述

我正在从 MongoDB (mLab) 实例中提取数据。

当我去编辑一个项目时,我希望当前项目的值(在加载此组件之前已经在我的 redux 存储中的数据)显示在此处的输入上:

图片

我已经测试过将组件的状态设置为 ``state = { name: this.props.item.name || "" }``

就是这样。我想如果我在渲染时将值加载为状态,输入的值会出现在那里。

import _ from "lodash";
import React from "react";
import InputField from "components/inputs/InputField";
import { withRouter, Link } from "react-router-dom";
import { connect } from "react-redux";
import { editExercise } from "actions/exerciseActions";

class ExerciseEdit extends React.Component {
  state = { name: "" };

  onChange = e => {
    this.setState({ [e.target.name]: e.target.value });
  };

  onSubmit = e => {
    e.preventDefault();

    const { history } = this.props;
    const { id, exerciseId } = this.props.match.params;
    const exerciseProps = { ...this.state };

    console.log(this.props.match.params);

    this.props.editExercise(id, exerciseId, exerciseProps, history);
  };

  render() {
    const { errors } = this.props;
    return (
      <div>
        <h1 className="title is-3">Edit your exercise</h1>
        <form onSubmit={this.onSubmit}>
          <InputField
            label="Name"
            name="name"
            type="text"
            value={this.state.name}
            onChange={this.onChange}
            errors={errors}
          />
          <Link
            to={`/workouts/${this.props.match.params.id}`}
            className="button is-danger is-large"
            style={{ marginTop: "20px" }}
          >
            Cancel
          </Link>
          <button
            type="submit"
            className="button is-primary is-large"
            style={{ marginTop: "20px" }}
          >
            Submit
          </button>
        </form>
      </div>
    );
  }
}

const mapStateToProps = ({ workouts }) => {
  return { workouts };
};

export default connect(
  mapStateToProps,
  { editExercise }
)(withRouter(ExerciseEdit));

我希望看到我的输入包含当前项目的名称值,这样用户就可以在编辑之前看到它的当前值。

标签: reactjsmongooseredux

解决方案


您应该使用componentWillReceiveProps组件生命周期。像这样

class ExerciseEdit extends React.Component {
    componentWillReceiveProps(nextProps) {
        if (nextProps.item.name) {
           this.setState({ name: nextProps.item.name })
        }
    }
}

推荐阅读