C
C
cosonicsq2019-11-04 22:50:11
React
cosonicsq, 2019-11-04 22:50:11

A few questions about React code.?

Please help me understand some things in the code that they do. I commented out the lines I didn't understand. Only 5 lines of code)

this.setState(
      {
        data, shift: Object.keys(data)[0]             // (1)   
      }, this.filter                                               // (2)
    );
  };

  onClick = ({
    target: {                                                   //(3)
      dataset: { shift }
    }
  }) => {
    this.setState(() => ({ shift }), this.filter);            // (4)
  };

    return (
      
        {days.map((day, i) => (
          <button
            key={day}
            onClick={() => this.loadDay(i)}                                  // (5)
            className={i === this.state.day ? "active" : ""}
          >
            {day}
          </button>
        ))}
   
    );
  }
}

Questions:
1) -it returns the name of the first property of the object as an array? 2) Why is the method passed as the second parameter ? what is he doing at the moment? 3) Why is the object passed to the method ? And what does he do? 4) Again, why is the method passed as the second parameter here again ? 5) Why is an anonymous function passed to the attribute and not just a method ? Object.keys(data)[0]data
setStatefilter
onClicktarget
filter
onClick() => this.loadDay(i)this.loadDay

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Egor Zhivagin, 2019-11-05
@cosonicsq

1) Object.keys() -- returns an array of object keys. [0] -- selects the first element of this array
2) This is a callback, the method is called immediately after updating the state. Read the React documentation in the section about setState and its call arguments
3) Read about destructuring. This is the destructuring of the argument that comes into the function. In this case, the standard event object. Similarly:

onClick = event => {
const shift = event.target.dataset.shift;
...
}

4) See point 2
5) Because you need to not only call the function on click, but also pass the i argument to it. But this particular implementation is bad practice.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question