[英]How can i outsource functions that use state and do setState
I have a class which has many functions, i wish to outsource these functions and put each group of function inside a file of their own and then use them by importing and calling them. 我有一个包含许多功能的类,我希望将这些功能外包,并将每组功能放入各自的文件中,然后通过导入和调用它们来使用它们。
Usually this is very simple, you simply put the function bodies inside another file and then export them, but in my case i use this.state
and this.setState
, is it still possible to outsource these function? 通常,这非常简单,您只需将函数主体放在另一个文件中,然后将它们导出,但是在我的情况下,我使用this.state
和this.setState
还是可以外包这些函数的? if not, is there a better practice? 如果没有,是否有更好的做法?
Thank you. 谢谢。
I just knocked this up real quick with no testing whatsoever, tell me if this is kinda what you were looking for? 我只是在没有任何测试的情况下很快就把它敲了出来,请告诉我这是否是您想要的?
window._stateManager = new StateManager();
class X extends React.Component {
constructor(props) {
super(props);
_stateManager.addStateFunction(this.setState.bind(this));
}
}
class StateManager() {
constructor() {
this.stateFunctions = [];
}
addStateFunction(ss) {
this.stateFunctions.push(ss);
}
updateStates(obj) {
this.stateFunctions.forEach(ss => {
ss((state => {
// here you have access to "this.state" as state
return Object.assign({}, state, obj);
// whatever you return from this function changes the state of the react component
}))
})
}
}
Why you want to update the state by the function that doesn't belong to your component or child component. 为什么要通过不属于您的组件或子组件的功能更新状态。 It doesn't make sense. 这没有道理。 You want to use redux there will be a single source of state of your entire App stored in the store. 您想使用redux,那么整个应用程序的状态源将存储在商店中。 All your state update logic will be separated in reducer and you would have access to action creator that can update your App's state. 您所有的状态更新逻辑都将在reducer中分离,并且您可以访问可更新应用程序状态的操作创建者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.