【问题标题】:How to do loop in json file in react如何在反应中在json文件中循环
【发布时间】:2021-09-24 10:27:19
【问题描述】:

我需要基本帮助。

我有一个数组。当我点击屏幕上的某个链接时,我只想看到他们的页面,我指的是他/她的名字,而不是全部。

首先,用户页面包含所有用户。如果我点击其中一些,我想去她/他的页面。我该怎么做?

Users 有用户 ID,所以它可以帮助你。

ProfilePage 代码:(它为所有用户提供 item.name)

const ProfilePage = () => {
  const { posts, users } = useContext(UserContext);

  return (
    <>
      {users.map((item, index) => {
        return (
          <>
            <h1>{item.name}</h1>
          </>
        );
      })}
    </>
  );
};

用户页面代码:

return (
    <>
      {users.map((item, index) => {
        return (
          <>
            <a href={`/profile/${item.username}`}>
              <List className={classes.root}>
                <ListItem alignItems="flex-start">
                  <ListItemAvatar>
                    <Avatar alt="Remy Sharp" />
                  </ListItemAvatar>
                  <ListItemText
                    primary={item.email}
                    secondary={
                      <React.Fragment>
                        <Typography
                          component="span"
                          variant="body2"
                          className={classes.inline}
                          color="textPrimary"
                        >
                          {item.name}
                        </Typography>
                        {<br />}
                        {item.username}
                      </React.Fragment>
                    }
                  />
                </ListItem>
                <Divider variant="inset" component="li" />
              </List>
            </a>
          </>
        );
      })}
    </>
  );

用户页面图片:

个人资料页面图片:(第一个用户页面。它应该只显示 1 个名称,而不是全部,我知道我使用了错误的地图)

【问题讨论】:

    标签: javascript json loops dictionary


    【解决方案1】:

    const ProfilePage = () => {
      const { posts, users } = useContext(UserContext);
    
      const { name } = useParams();//Your dynamic route name. Example: <Route path="/profile/:name">
      const filteredUsers = users.filter(item => item.name === name);//Find all users with name Bret
    
      //Ideally, you need to make a router with a dynamic ID, then there will be a unique user. Example: <Route path="/profile/:id">
      //const { id } = useParams();
      //const filteredUsers = users.filter(item => item.id === id);
    
      return (
        <>
          {filteredUsers.map((item, index) => {
            return (
              <>
                <h1>{item.name}</h1>
              </>
            );
          })}
        </>
      );
    };

    【讨论】:

    • 你好,“你的动态路由名称”是什么意思?我将此用于配置文件页面路由:
    • 等待我像你的代码一样更新它并且它有效!非常感谢
    • 试试+post.userId === +userId
    • '+' 从字符串中返回一个整数
    猜你喜欢
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 2012-02-02
    • 2017-02-03
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多