I am making a simple React.js website, without Redux. I have a component, A, that procedurally makes x children, all of which are another component, B. When the component B is created, it is given a reference to A, and it then updates the state of A, by adding to a list field in the state.
This causes an issue - all of the B components attempt to chance the state of A at the same time, and thus, all of them fire the setState method with the list field being an empty list - []. And then, the list field incorrectly become a list with only one element.
How would one go about updating A's state several times, at the same time?
Here's what's happened in practice:
EXPECTED RESULT: A's titleList includes many elements. ACTUAL RESULT: A's titleList includes only one element.
A's GeneratePathNode() (which is indeed binded):
GeneratePathNode() {
let directionlessTextElements = [ // ... many <div/>'s
];
return <>
{
directionlessTextElements.map((element, i) => {
let textElement = element;
return <MyPathNode textElement={textElement}
InsertTitleToParent={this.InsertTitleToParent}
key={i}/>;
})
}
</>;
}
A's InsertTitleToParent():
// Passed as a prop to the MyPathNode's.
InsertTitleToParent(title){
this.setState({titleList: [...this.state.titleList, title]});
console.log([...this.state.titleList, title]); // Prints only a single element in a list.
}
A's render():
render() {
return (
<div>
{/*A lot of irrelevant elements*/}
{this.GeneratePathNode()}
{/*A lot of irrelevant elements*/}
);
}
B's constructor():
constructor(props) {
super(props);
// ... A lot of irrelevant code lines.
let titleText = "some text";
this.props.InsertTitleToParent(titleText);
}