How call React's setState function from outside of any component, like a utility function?

后端 未结 4 1522
忘了有多久
忘了有多久 2021-01-22 08:16

I have an app where I want to move the read, write operations to a utility file i.e. away from component. I am trying to do it this way.

component.js

imp         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-22 08:35

    This is not a good idea to extract methods that rely on the context (component instance) to utility functions, primarily because this requires to take additional actions to make them work.

    Since this.setState is passed as a callback, it should be either bound to proper context:

    saveData(this.setState.bind(this), data);
    

    Or utility function should be defined as regular function and be called with proper context:

    function saveData(data) {
        this.setState(data);
    }
    
    class App extends Component {
        saveContent() {
            saveData.call(this, data);
        }
        ...
    }
    

    This is the case where inheritance is preferable because it allows to get proper context naturally. saveData can be reused via a mixin.

    It can be assigned directly to class prototype:

    function saveData(data) {
        this.setState(data);
    }
    
    class App extends Component {
        // saveData = saveData
        // is less efficient but also a correct way to do this
        saveContent() {
            this.saveData(data);
        }
        ...
    }
    App.prototype.saveData = saveData;
    

    Or be applied via a decorator:

    function saveData(target) {
        return class extends target {
            saveData(data) {
                this.setState(data);
            }
        }
    }
    
    
    @saveData
    class App extends Component {
        saveContent() {
            this.saveData(data);
        }
        ...
    }
    

提交回复
热议问题