【发布时间】:2016-11-23 10:31:44
【问题描述】:
如果有一个用户列表并且每个条目都有一个按钮 »EDIT«。如果用户点击它会发生以下情况:
- 向服务器请求表单
- 将组件
<UserEditForm />添加到条目中,扩展条目的内容
除了一件事之外,这很好用:如果单击更多按钮,则表单的每个实例都会收到请求的最后一个用户表单的数据。那是因为我在该州只有一个userform 属性。
为了解决这个问题,我想将userform 交换为userforms,它应该/可能是这样的对象:
userforms: {
<id of first instance>: { … }, //formdata
<id of second instance>: { … },
…
}
但由于我是 React/Redux 的新手,我真的不知道该怎么做,也不知道真正做到这一点的“正确”方法或最佳实践是什么。
我的想法是像这样创建一个更高阶的组件:
import React from 'react';
import {connect} from 'react-redux';
import {uuid} from '../../helpers/uuid';
export const formdatainstance = (FormInstance) => {
let id = null;
class FormDataMapper extends React.Component {
constructor (props) {
super(props);
id = uuid();
}
render () {
//extract the formdata from the state
//using the id
return <FormInstance { ...this.props } />
}
}
const mapStateToProps = (state) => {
console.log(id); //is null for one run
return {
userforms: state.userforms
};
};
return connect(mapStateToProps)(FormDataMapper);
}
所以在 List 组件中我可以:
import UserEditForm from './UserEditForm';
import {formdatainstance} from './formdatainstance';
const MappedUserEditForm = formdatainstance(UserEditForm);
class List extends React.Component {
render(){
return (
{users.map(user => {
//more stuff
<MappedUserEditForm />
//more stuff
})}
);
}
}
所以我的问题:这是一个好主意吗?如果是,那么进行清理的正确方法是什么,那么在组件的生命周期中,我应该在何时从状态中删除数据?还有其他更简单的方法吗?
感谢您的帮助!
【问题讨论】:
-
您想在状态中保留多个表单数据(针对每个用户)吗?或者你有一个表单数据的状态对象就足够了,它由用户填充并在你为另一个用户单击编辑时重置?你也可以从你的减速器中发布相关代码吗?
-
我想为渲染表单的每个实例提供唯一的表单数据。因此,如果列表中有三个用户,我想最终得到三个表单,显示每个用户的数据,可以单独编辑和提交。
-
我也很乐意抽象这个功能,以便它可以应用于代表系统中其他实体的另一种形式的其他组件。
标签: reactjs redux react-redux redux-form