K
K
Kesio2021-08-04 15:52:13
React
Kesio, 2021-08-04 15:52:13

Why is the component not rendered when moving to another page?



when I click on the button to go to another page, the new App component is not rendered for me :

<Router>
            <div>
                <Header />
                <Switch>          
                    <Route path="/" exact>
                        <Main />
                    </Route>
                    <Route path='/shop/jordan'>
                        <Shop link="https://60fbcfc191156a0017b4c8bb.mockapi.io/jordan" />
                    </Route>
                    <Route path='/shop/run'>
                        <Shop link="https://60fbcfc191156a0017b4c8bb.mockapi.io/run" />
                    </Route>
                    <Route path='/shop/basketball'>
                        <Shop link="https://60fbcfc191156a0017b4c8bb.mockapi.io/basketball" />
                    </Route>
                    <Route path="/shop" exact >
                        <Shop link="https://60fbcfc191156a0017b4c8bb.mockapi.io/run" />
                    </Route>       
                </Switch>
            </div>

        </Router>


After switching to another page, the props changes, the Item component should be re-rendered.
Here is the Item:
import React from 'react';
import stylus from '../shop.module.scss';

function Items(props) {
    const [items, setItems] = React.useState([])
    const [link, setLink] = React.useState(props.link)
    React.useEffect(() => {
        fetch(link)
            .then(response => response.json())
            .then((json) => {
                return setItems(json)
            })
    }, [link])

    return (
        <div className={stylus.items}>
            {
                items.map(obj =>
                    <div className={stylus.item} key={obj.id}>
                        <img src={obj.img} alt="" />
                        <h4>{obj.name}</h4>
                        <h4>Price: {obj.price}</h4>
                    </div>
                )
            }
        </div>
    )
}

export default Items;

It is updated only after the page is updated on its own, but I wanted to re-render the Item component when changing the props.
I did not understand how to do this on my own :D

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-08-04
@Kesio

Or maybe it still renders? The value of link is not updated when props.link is changed, so the effect does not work - hence the lack of external changes on re-renders.
Remove the link, you don't need it here, just use props.link in the effect:

React.useEffect(() => {
  fetch(props.link)
    .then(r => r.json())
    .then(setItems);
}, [ props.link ]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question