简体   繁体   中英

React Component doesn't rerender when the state is changed

I am working on a small React project to get to learn more about it.

The project can make and view groups and in the groups you can store images, videos...

So the problem is when I open one of those groups and while I'm in it if I try to change to another group the component doesn't rerender and I have the same information.

Here's some of the code:

App:

function App() {
  const [chosenGroup, setChosenGroup] = useState({});

return (
    <Router>
      <Header setChosenGroup={setChosenGroup}/>
      <Routes>
        <Route 
          path="/Group/:group_name" 
          element={<Group group={chosenGroup} />}
        />
      </Routes>
    </Router>
  );

}

Header (Where I choose the group):

function Header(props) {
  const setChosenGroup = props.setChosenGroup;

  return (
    <>
      <Top>
        <Image src={SiteLogo} />
        <GroupsBtn>
          MY GROUPS
        </GroupsBtn>
        <AllGroupsCont>
          <AllGroups>
            {myGroupDB.map((group, index) => {
              return (
                <StyledLink to={`/Group/${group.group_name}`} key={index}>
                  <Group onClick={() => {
                      setChosenGroup(group);
                    }}>
                    {group.group_name}
                  </Group>
                </StyledLink>
              );
            })}
          </AllGroups>
        </AllGroupsCont>
      </Top>
    </>
  )
}

Group:

function Group(props) {
  const param = useParams();
  
  return (
    <Main>
      <Top>
        <GroupTitle defaultValue={param.group_name} />
        <SaveButton className="saveButtonGroup" src={SaveIcon} />
        <DateCreated>Date created: {creationDate}</DateCreated>
      </Top>
      <Center>
        <GridContainer>
          {group.photos.map((photo) => {
            <Image src={photo.url} />;
          })}
        </GridContainer>
      </Center>
      <Bottom>
        <GoBackBtn onClick={() => navigate(-1)}>GO BACK</GoBackBtn>
        <SaveBtn>SAVE</SaveBtn>
      </Bottom>
    </Main>
  )
}

I checked the components in the browser and the state does indeed update so the problem is something else.

This might solve it

 <Group onClick={() => { setChosenGroup({...group}); }}>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM