0

我正在尝试将表格行对象传递给 Redux-Form 以编辑对象值。

在此处输入图像描述

这里是ViewStudents.js文件的一些内容

  handleEdit(e, student) {
    e.preventDefault();
    const { dispatch } = this.props;
    dispatch(allActions.editStudents(this.state));
    this.setState({
      firstName: student.firstName,
      lastName: student.lastName
    });
    this.props.history.push("/EditStudents");
  }

  <button  onClick={e => this.handleEdit(e, student)}>Edit</button>


function mapStateToProps(state) {
  const { students } = state.viewStudents;
  return {
    students
  };
}

export default connect(mapStateToProps)(ViewStudents);

这里是EditStudents.js的一些内容

在此处输入图像描述

      constructor(student) {
        super(student);
        this.state = {
          firstName: student.firstName,
          lastName: student.lastName
        };
      }

      handleSubmit(e) {
        e.preventDefault();
        const { dispatch } = this.props;
        dispatch(allActions.editStudents(this.state));
        this.setState({
          firstName: "",
          lastName: ""
        });
        this.props.history.push("/ViewStudents");
      }

function mapStateToProps(state) {
  const { student } = state.addStudents;
  return {
    initialValues: {
      firstName: state.student.firstName,
      lastName: state.student.lastName
    }
  };
}

export default reduxForm({
  form: "EditForm",
  validate,
  mapStateToProps
})(EditStudents);

问题是,这个对象的值没有传递给编辑表单,尽管我在mapStateToPropsinitialValues中绑定并在构造函数中传递了这个对象

如何绑定它并正确传递表格行中的单击对象并编辑/保存该对象

4

1 回答 1

0

我可以看到一些小问题。您不应该使用状态来选择要编辑的项目。始终认为用户会在任何项目处刷新页面。因此,您应该使用 React Router Splat 来传递唯一的值/ID。

http://localhost:3000/EditStudents/1

为此,您需要在添加时为每个学生添加一个唯一的 ID,然后将该 ID 与路线一起使用。

<Route path="/EditStudents/:studentId" component={EditStudents} />

然后您可以读取 ID 并加载到 componentDidMount

componentDidMount() {
    const { dispatch } = this.props;
    var {studentId } = props.match.params;
    dispatch( { type: "LOAD_STUDENT", studentId });
}

使用刷新状态(请求、成功)有清除数据的效果。因此,任何初始状态都会丢失。

请注意,您还使用服务来加载数据。实际上,您应该使用异步 thunk 将数据加载到 redux 中。你应该只从 redux 获取数据,然后使用中间件来持久化数据。

https://github.com/reduxjs/redux-thunk

https://codesandbox.io/s/MQnD536Km

于 2019-09-03T21:07:36.260 回答