javascript - 将 props、state 和 [this] 值传递给实用程序文件

标签 javascript reactjs

将 props、state 和 [this] 值传递给实用程序文件的最佳方法/实践是什么?

我的 utils 文件只是我导出的 3 个函数。请检查我提供的示例代码。我只是将 [this] 直接传递给函数,这看起来有点奇怪,就像我做错了事情一样。只是想知道处理非组件文件时是否有更好的方法

谢谢

// index.js
utils.saveData(data, this);

// utils.js
const saveData = (data, _this) => {
  const { props } = _this;
  fetch(`https:/someURL/update`, {
    method: 'post',
    body: JSON.stringify(data)
  })
  .then(() => {
    props.history.push({
      pathname: `/thankyou`
    });
  })
  .catch(() => {
    // my want set state here or use [this]
  });
};

最佳答案

遵循简单责任原则,你的实用函数应该只做一件事,不要混合搭配。

我建议您使用async/await,但如果您不能使用回调

// utils.js
const saveData = (data, cb) => {
  fetch(`https:/someURL/update`, {
    method: 'post',
    body: JSON.stringify(data)
  })
  .then(() => cb())
  .catch(cb);
};

在主文件中

//Component.js
const callback = (err) => {
   if(err) {
      // I want set state here or use [this]
   } else {
      this.props.history.push({
        pathname: `/thankyou`
      });
   }
}

utils.saveData(data, callback);

现在该实用程序不知道数据来自哪里,saveData 实用程序唯一会调用 api 并表示其成功或失败。

关于javascript - 将 props、state 和 [this] 值传递给实用程序文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57862991/

相关文章:

javascript - 部署 Angular 项目错误类型 MIME (text/html)

reactjs - this.state 在方法中未定义

javascript - 所有者/父级与所有者/单个子级的 setState

html - 移动设备上的表单字段缩小得太小

javascript - Matter.js 禁用不同复合 Material 之间的碰撞

javascript - 单击按钮时如何避免刷新asp.net中的文本框值?

javascript - 使用 jquery 显示子元素的悬停元素

javascript - Action 图标显示为纯文本

javascript - 如何从外部reactjs获取变量

javascript - 在 underscore.js _.where 中使用变量