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

React Js, How can I save multiple data in onClick?

我有table,由x值和y值定位。这些值保存在数据库中。我正在使用 react dnd 来定位这些 table

我现在要做的是一键保存所有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>

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

可以像上面那样做吗?还是有其他方法可以一键保存所有 table 的数据?

提前致谢..

--编辑全错误

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

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

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} ...]

当然,您将不得不修改 action/reducer 以处理所有数据的数组。

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