D
D
dimmma772015-11-08 10:35:20
JavaScript
dimmma77, 2015-11-08 10:35:20

How to add data to an array using foreach in react?

There is an array in this.state.massiv . How can I add a new element to this array? Will push be ok? Is it also possible to somehow transfer data from one component to another without using this.state or this.props? And the last question: ajax request inside foreach, does foreach have a callback? how to find out when the whole array will be sorted out and only after that execute the following code?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Gushchin, 2015-11-08
@dimmma77

1. push mutates the array. We read this and never mutate state. In ES6, you can add an element to an array like this:
2. These components should receive only through props. Of course, you will have some of the components as a controller-view (connected to the store and will receive data through events \ context \ somehow), but there should be few such controllers, really few - mainly at the top levels of the tree.
3. Concerning ajaxa - take out such logic in a business layer. To your action creators, for example. Then you will not have such problems: make a request -> when it completes send the appropriate action (success, failure) -> store handles the action, changes its state -> controller view receives new data and
renders 4. ES6 has promises

const someArr = [];
const doAjaxJob = el => fetch('some-url', .... );
const p = Promise.all(someArr.map(doAjaxJob)); // <-- сюда можно подписаться

PS And most importantly - do not turn a good functional style into spaghetti

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question