In my project, I'm looping through cards in my Child Component, and updating the Parent's state with ones where I activate an event of 'swiping right' on the card to favorite. The parent's state keeps track of all favorites by adding the favorited card to the array.
I'm passing down a function (updatestate
)from the Parent Component, App
, to the Child, Main
, that allows the Child to call .setState()
and append to the array in the Parent state.
But, when I activate the eventhandler onSwipedRight
inside the Child Component, the parent's state gets updated as planned with the new Card, but nothing below the <Card>
in Main
gets rendered automatically for the next card, as it should. If I tap the screen, then the next card/picture renders only then.
Any ideas? Am I missing some binding or need to do some componentDidMount or anything so the code in child component, Main
, renders even after I activate the event handler that updates the parent state?
Basically, is there a tool in React to make sure something renders or at least waits for it to render? (post event handling which sets the parents state in my case)
collection = imagedata;
//collection is the data (local JSON) i'm looping thru via .map in Main Component
const RootStack = StackNavigator(
{
Main: {
screen: Main}
}
);
export default class App extends Component<{}> {
constructor(props) {
super(props);
this.state = {
favoritesList: []
};
}
updateArr=(itemname, url)=>{this.setState({ favoritesList: [...this.state.favoritesList, {"item_name":itemname, "url":url}]})};
render() {
return <RootStack screenProps={{appstate: this.state,
updatestate: this.updateArr}}
/>;
}
}
class Main extends React.Component {
render() {
var updatestate = this.props.screenProps.updatestate;
const contents = collection.map((item, index) => {
return (
<Card key={index}
onSwipedRight={() => {updatestate(item.item_name,item.url)}}
>
<View> //THIS and anything after <Card> doesn't render for the next card automatically if I do 'onSwipedRight'
<Image
source={{uri: item.url}} />
</View>
</Card>
)
},this);
return (
<View>
<CardStack>
{contents}
</CardStack>
</View>
);
}
}
(abbreviated) Project structure:
App
|__ Rootstack
|
|__Main
UPDATE (more info):
Just to test the event handler, I added in a function that doesn't set the state of the parent, and had <Card>
call that on the event handler -- it works perfectly and the child component <Card>
renders perfectly. It seems that it's the updatestate
function passed down from the parent to the child that acts to call .setState()
upstream that for some reason is causing the Child to not render/not finish rendering after the event handler.
class Main extends React.Component {
render() {
var updatestate = this.props.screenProps.updatestate;
var newfunc = (a, b) => {console.log('a:', a, 'b:', b)};
const contents = collection.map((item, index) => {
return (
<Card key={index}
newfunc(item.item_name,item.item_name);}}
// onSwipedRight={() => {updatestate(item.item_name,item.url); }}
>