简体   繁体   中英

Default function parameter value from React component state

Today I did a review for my colleague and I found a function definition that interested me. He implemented a function inside a react component with default parameter values if the function call is not provided with an argument. He used a state value as a default parameter.

It looked like this example:

class CustomComponent extends React.Component {
    constructor(props) {
         this.state = {
             loadedData = [], // array of objects
         };

         this.filterDates = (fromUtc, toUtc, loadedData = this.state.loadedData) {
             // do something with 'loadedData' based on time range 'fromUtc' and 'toUtc'
         }
    }
}

He could not provide me a good explanation. Only that it works in his implementation.

I have always used 'static' default parameter values (like [] , number, etc.) I am curious if it is ok to use some kind of 'dynamic' default parameter, which changes when state changes.

Is it ok to write it like this? Could be there a problematic case?

According to Airbnb Javascript Style Guide -es6 default parameters this approach is good. However I question assigning default value to state which is mutable by definition unless it's desired effect. Default parameter shouldn't be mutable. Personally I see such approach for the first time and I think it's not intuitive but maybe it's just my experience.

In my opinion code below is cleaner, easier to understand and less buggy:

class CustomComponent extends React.Component {
    constructor(props) {
         this.state = {
             loadedData = [], // array of objects
         };

         this.filterDates = (fromUtc, toUtc, loadedData = []) => {
             // do something with 'loadedData' based on time range 'fromUtc' and 'toUtc'
         }
    }
}

In the constructor, this.state is a simple object without any magical feature of states. So, loadedData = this.state.loadedData is the same as loadedData = [] but the second one is more readable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM