简体   繁体   中英

React Function components in combination with states and (arrow)functions

I learned the basics of JavaScript and React and today I was revisiting my React learning. To my surprise all class-based components are a goner and everything is a function component now. This confuses me a lot because:

I am used to writing:

state = {
todos = [ {sometodo: content}, {sometodo: content}]
}

someFunction = (para) => {
do something
}

but now I apparently have to write:

function App() {

  const [todos, setTodos ] = useState([
      {id: 1, content: 'buy some milk'},
      {id: 2, content: 'play mario kart'}
  ]);

  const deleteTodo = (id) => {
    console.log(id);
  }

In the essence, I don't mind because I understand Reacts will to innovate. But I was wondering if throwing a const everywhere is the right way to code this. I honestly just need some confirmation if I am doing this right? Cause if I look for arrowfunctions in React, all I get is the old pages with classbased components.

Oh and a sidequestion: Do you now just make a function component of everything?

Thanks in advance!

Class components are still very much alive and in use. Functional components have become more popular recently with the intruduction of Hooks. useState is a hook, and allows you to turn a functional component into a stateful one, without having to convert to a class component. So you can write things much cleaner with functional components. I personally still use class components a lot, especially for larger, beefier components.

I don't see anything incorrect with what you wrote at all. (Except it should be state: [...] in your first line of code, not state = [...] )

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