P
P
Pavel2021-10-10 23:16:57
React
Pavel, 2021-10-10 23:16:57

Why doesn't adding react components through a loop work?

When the button is pressed, the code fetches the data via ajax into the database and outputs it through a loop. But only one block with the last record is created. I don’t understand why it works like this, because the data is exactly all there.

Received data:

  • ['1', 'Pavel', '1000.25', '2021-10-07']
  • ['2', 'Anton', '5541', '2021-10-30']
  • ['3', 'VVV', '1000', '2021-10-14']


// В другом файле
const Article = (props) => {
    return (
        <div>
            <h1>Статья</h1>
            {props.name}
        </div>
    );
};


function App() {

  const [article, setArticle] = useState([]);

  function clickHandler () {
    fetch("http://192.168.1.50/text.php", {
      method : "POST",
      header : {
        'Content-Type' : 'application/x-www-form-urlencoded; charset=utf-8',
      },
      body : JSON.stringify({ action : 1 })
    })
    .then (response => response.json())
    .then (response => {
      createArticle(response);  
    })
  };

  const createArticle = (element) =>{
    element.forEach(el => {
      setArticle(article.concat( <Article name={el[1]} key={article.length} /> ))
    });
  };

  return (
    <div className="App container my-3">

      <section>
        {article}
      </section>
      
      <button className="btn btn-success" onClick={clickHandler}>Получить данные</button>
    </div>
  );
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Masson, 2021-10-11
@PAPASKAS

Dear mother...
Come here friend, I will open the world of SIMPLE CODE for you.

import "./styles.css";

const Article = ({ name }) => {
  return (
    <div>
      <h1>Статья</h1>
      {name}
    </div>
  );
};

function App() {
  const [article, setArticle] = useState([]);

  function clickHandler() {
    fetch("http://192.168.1.50/text.php", {
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
      },
      body: JSON.stringify({ action: 1 })
    })
      .then((response) => response.json())
      .then((response) => {
        setArticle(response);
      });
  }

  return (
    <div className="App container my-3">
      <section>
        {article.map((value, index) => (
          <Article key={index} name={value.name} />
        ))}
      </section>

      <button className="btn btn-success" onClick={clickHandler}>
        Получить данные
      </button>
    </div>
  );
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question