W
W
webe2018-06-27 04:25:30
React
webe, 2018-06-27 04:25:30

How to call a dispatcher with a value?

const todos = [1,.....10000]
  render() {
    return todos.map(item => (
      <div key={item.id} onClick={()=>this.props.toggleTodo(item.id)} />
    ));
  }
}

On click, dispatch to a store with an ID
This code works, but it is a hack, because it creates 10,000 anonymous functions, and as I understand it, they then hang in memory
How to dispatch to a store with an ID but without a crutch with an arrow function?
Are there any other options?
Let me remind you that our ID is known only inside the map loop.
Tell me plz.
I only know the method:
1) take out the React Class Component div and throw this.props.toggleTodo and item into it,
i.e. it will be like this
<Todo toggle = {this.props.toggleTodo} data={item}>

But something is somehow not a very option, you need to stir up the whole RCC for the sake of 1 call ...
Are there any other options?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-06-27
@webe

To solve this problem, you can use the data attribute:

handleTodoClick = e => {
  const { id } = e.target.dataset;
  this.props.toggleTodo(id);
};
render() {
  return todos.map(item => (
    <div key={item.id} data-id={item.id} onClick={this.handleTodoClick} />
  ));
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question