I'm not so good with arrow functions and would like some practice changing from arrow function to regular function. This is within React.
render() {
const todoItems = this.state.todos.map(item => <TodoItem key={item.id} item={item} handleChange={this.handleChange}/>)
CodePudding user response:
There are a few general forms of arrow functions.
arg1 =>
is strictly for one argument(arg1, arg2) =>
for more than one argument, enclose in parentheses.
On the other side of the arrow, there are another 2 forms:
=> value
returns value (or the result of an expression)=> {someStatements;}
does not implicitly return anything.
When converting to functions, follow this table:
arg1 =>
becomesfunction(arg1)
(arg1, arg2) =>
becomesfunction(arg1, arg2)
=> value
becomesfunction(args) { return value }
=> { someStatements;}
becomesfunction(args) { someStatements;}
So in this particular case, given todos.map(item => <Component />)
, the function is item => <Component />
and working backwards from the table above we can see that this is equivalent to the function function(item) { return <Component />; }
The full line looks like this:
const todoItems = this.state.todos.map(
function(item) {
return <TodoItem key={item.id} item={item} handleChange={this.handleChange}/>
}
)
See also Arrow Function Expression on MDN
CodePudding user response:
If you want transform an arrow function to regular function, follow this code:
const todoItems = this.state.todos.map(handleMap)
function handleMap(item) {
return <TodoItem key={item.id} item={item} handleChange={this.handleChange}/>
}
But, I recommend to use function components and React hooks. Read this artice: https://reactjs.org/docs/hooks-intro.html