将 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/