首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React Js,如何在onClick中保存多个数据?

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

Stack Overflow用户
提问于 2017-02-13 16:44:10
回答 1查看 3K关注 0票数 0

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

我现在想做的是一次点击保存所有表格的位置。为了做到这一点,我编写了如下代码。

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-13 18:27:13

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

代码语言:javascript
复制
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应该是如下所示的数组:

代码语言:javascript
复制
[{id, x, y}, {id, x, y} ...]

当然,您必须修改action/reducer来处理所有数据的数组。

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42199852

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档