【问题标题】:pass table row object from table and edit it using Redx-Form从表中传递表行对象并使用 Redx-Form 对其进行编辑
【发布时间】:2020-01-04 22:51:50
【问题描述】:

我正在尝试将表格行对象传递给 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);

问题是,这个对象的值没有传递给编辑表单,虽然我在 ma​​pStateToPropsinitialValues 中绑定并在 constructor 中传递了这个对象

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

【问题讨论】:

    标签: reactjs redux-form redux-thunk react-router-dom reducers


    【解决方案1】:

    我可以看到一些小问题。 您不应该使用状态来选择要编辑的项目。始终认为用户会在任何项目处刷新页面。因此,您应该使用 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多