Reputation: 63
I am having a problem with the loop. below sample code, notice that I have an array of objects as a dummyData.
the Component0 loads Component1 and this component is in charge of the initial loop, each data from the dummyData represents Component2 which has its own state. On the last part "return" of Component1, I also manually call the Component2 3x with manual props.name.
When you run this code using this code sandbox, check the console for the logs. Noticed that when you click any STATIC it only renders the Component2 but when you click any DYNAMIC it will render the Component1 which is wrong because this will initiate the loop again.
Sandbox: https://codesandbox.io/embed/sharp-leftpad-4t9yi
import React, { useState } from "react";
import ReactDOM from "react-dom";
const dummyData = [
{ name: "DYNAMIC 1" },
{ name: "DYNAMIC 2" },
{ name: "DYNAMIC 3" },
{ name: "DYNAMIC 4" },
{ name: "DYNAMIC 5" }
];
const Component0 = () => {
console.log("FIRST RENDER");
return (
<div className="App">
<Component1 dataList={dummyData} />
</div>
);
};
const Component1 = props => {
console.log("SECOND RENDER");
let listDom = null;
let listDoms = [];
props.dataList.map(data => {
listDom = Component2(data);
listDoms.push(listDom);
return 1;
});
return (
<React.Fragment>
<Component2 name="STATIC 1" />
<Component2 name="STATIC 2" />
<Component2 name="STATIC 3" />
{listDoms}
</React.Fragment>
);
};
const Component2 = props => {
let showed = true;
const [listState, setListState] = useState(showed);
const handleClick = props => {
showed = listState ? false : true;
setListState(showed);
};
if (listState) {
console.log("RENDER : " + props.name);
return (
<div key={props.name}>
<a href="#!" onClick={() => handleClick()}>
<h1>{props.name}</h1>
</a>
</div>
);
} else {
return null;
}
};
const rootElement = document.getElementById("root");
ReactDOM.render(<Component0 />, rootElement);
Upvotes: 1
Views: 1776
Reputation: 942
Replace this
listDom = Component2(data);
listDoms.push(listDom);
With
listDoms.push(<Component2 name={data.name}/>)
The way you were initializing the component in React was wrong. Also try using ForEach instead of Map method. :)
Upvotes: 1
Reputation: 962
You should update this:
let listDoms = [];
props.dataList.map(data => {
listDom = Component2(data);
listDoms.push(listDom);
return 1;
});
to this:
let listDoms = props.dataList.map(data => {
listDom = <Component2 key={data.name} name={data.name} />;
return listDom;
});
Hope this helps.
Upvotes: 3