Answer the question
In order to leave comments, you need to log in
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:
// В другом файле
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
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 questionAsk a Question
731 491 924 answers to any question