A
A
Anton2020-06-19 14:06:41
JavaScript
Anton, 2020-06-19 14:06:41

How to remove the dependence of components rendered by the .map method on each other?

Good day to all.

There is something like this:

function Example () {
    const [message, setMessage] = React.useState(false);
    const sendMessage = (id, message) => () => {
        const data = {
            ID: id,
            MESSAGE: message,
        };
        sendMessage(data); //Это действие Redux, оно особого отношения к делу не имеет.
        setMessage(true);
return (
    arr1.map(i) => {
        <Grid>
            <Button onClick={sendMessage(i, message)>
                Отправить
            </Button>
            {message !== null && (
                <font>Отправлено</font>
             )}
          </Grid>


The point is that if you press the Send button at any iteration of the arr1 array, the string is re-rendered at all iterations.
How to separate each element of the array into a separate component, with its own data inside?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2020-06-20
@Robur

1. they do not depend on each other, you change the state of the component and the render is called again. This is normal behavior.
2. message variable - one for all, if you change it, then a change will occur in all at once - "sent" will be added or deleted.
If you have a problem that you click send in one component, and "sent" appears in all - but you want each to have its own "sent" then you need to make a separate flag for each line. The best thing is to make what is inside the Grid a separate component and move the message / setMessage there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question