React Js,如何在onClick中保存多个数据?

时间:2017-02-13 08:44:10

标签: reactjs react-dnd

我有table,其值由xy定位。这些值保存在数据库中。我正在使用react dnd定位这些table

我现在要做的是一键保存所有表位。为此,我制作了如下代码..

constructor() {
 super();
 this.state = {
   tables: []
 }}

saveTables() {
 const { state, dispatch, tables } = this.props;
 this.state.tables.map((table) => {
  const data ={
    id: table.id,
    x: table.x,
    y: table.y,
  }
  dispatch(Actions.save(this.props.tables.channel, data));
 })
}

<button onClick={this.saveTables}>Save</button>

因此,当安装组件时,我将表的所有信息都记录到this.state.tables中。因此,对于saveTables()函数,我要做的是通过映射this.state.tables调度操作来为每个表保存xy的位置。但是,它会触发TypeError: action is undefined

的错误

是否有可能像上面那样做?或者是否有其他方法可以一键保存所有表格数据?

提前致谢..

- 编辑完整错误

TypeError: action is undefined[Learn More] app.js:54241:1 routerMiddleware/</</< http://localhost:4000/js/app.js:54241:1 saveTables/< http://localhost:4000/js/app.js:73190:9 map self-hosted saveTables http://localhost:4000/js/app.js:73184:7 bound saveTables self-hosted bound bound saveTables self-hosted ReactErrorUtils.invokeGuardedCallback http://localhost:4000/js/app.js:45316:7 executeDispatch http://localhost:4000/js/app.js:39166:5 executeDispatchesInOrder http://localhost:4000/js/app.js:39189:5 executeDispatchesAndRelease http://localhost:4000/js/app.js:38581:5 executeDispatchesAndReleaseTopLevel http://localhost:4000/js/app.js:38592:10 forEach self-hosted forEachAccumulated http://localhost:4000/js/app.js:50930:5 EventPluginHub.processEventQueue http://localhost:4000/js/app.js:38795:7 runEventQueueInBatch http://localhost:4000/js/app.js:45345:3 ReactEventEmitterMixin.handleTopLevel http://localhost:4000/js/app.js:45356:5 handleTopLevelImpl http://localhost:4000/js/app.js:45438:5 TransactionImpl.perform http://localhost:4000/js/app.js:50185:13 ReactDefaultBatchingStrategy.batchedUpdates http://localhost:4000/js/app.js:45084:14 batchedUpdates http://localhost:4000/js/app.js:48223:10 ReactEventListener.dispatchEvent http://localhost:4000/js/app.js:45513:7 bound

1 个答案:

答案 0 :(得分:2)

您可以映射需要保存的所有数据,然后发送操作(这样会更有效,因为您的应用只运行渲染例程一次)。

saveTables() {
  const { dispatch, tables } = this.props;
  const tableData = tables.map(table => ({
    id: table.id,
    x: table.x,
    y: table.y,
  });
  dispatch(Actions.save(tables.channel, tableData));
}

tableData应该是一个类似的数组:

[{id, x, y}, {id, x, y} ...]

当然,你必须修改动作/减速器来处理所有数据的数组。

至于您需要提供错误发生的代码(不仅仅是堆栈跟踪),但如果没有正在运行的示例,可能很难知道。