简体   繁体   English

React - 只显示被点击的用户

[英]React - Show only the clicked user

In the following app, I'm accessing the random user API and show a list of 12 users.在以下应用程序中,我正在访问随机用户 API 并显示 12 个用户的列表。

App.js应用程序.js

import React, { useState } from 'react'
import UserList from './components/UserList'

const App = props => {
  const [id, setID] = useState(null)
  console.log(`Passed variable to App.js is: ` + id)

  return (
    <>
      <UserList setID={setID} />
    </>
  )
}

export default App

UserList.js用户列表.js

import React, { useState, useEffect } from 'react'
import axios from 'axios'

const UserList = ({ setID }) => {
  const [resources, setResources] = useState([])

  const fetchResource = async () => {
    const response = await axios.get(
      'https://api.randomuser.me/?results=12'
    )
    setResources(response.data.results)
  }

  useEffect(() => {
    fetchResource()
  }, [])

  return (
    <ul>
      {resources.map(item => (
        <li key={item.name.first}>
          <div>
            <h2>{item.name.first} {item.name.last}</h2>
            <button
              onClick={() => setID(item.login.uuid)}
            >
              Details
            </button>
          </div>
        </li>
      ))}
    </ul>
  )
}

export default UserList

The above code is working.上面的代码正在工作。 But now I want that if I click on the button for any of those listed users, only that user get showed.但是现在我希望,如果我单击任何列出的用户的按钮,则只会显示该用户。

How can I do that?我怎样才能做到这一点?

The response JSON looks like this:响应 JSON 如下所示:

在此处输入图像描述

Easiest way would be to apply a filter on your ressources variable to only display the user with selected uuid.最简单的方法是对您的ressources变量应用过滤器,以仅显示具有选定 uuid 的用户。

To do that, first you need to share selected id with UserList component :为此,首先您需要与UserList component共享选定的 id:

App.js应用程序.js

<UserList id={id} setID={setID} />

Then update UserList accordingly:然后相应地更新 UserList:

UserList.js用户列表.js

const UserList = ({ id, setID }) => {

    return (
        <ul>
          { resources
               .filter(user => Boolean(id) ? user.login.uuid == id : true )
               .map(item => (
               <li key={item.name.first}>
                 <div>
                   <h2>{item.name.first} {item.name.last}</h2>
                   { Boolean(id) ? 
                     <button onClick={() => setID(null)}>
                       Hide
                     </button>
                     :
                     <button onClick={() => setID(item.login.uuid)}>
                       Details
                     </button> 
                    }
                 </div>
               </li>
              )
          }  
        </ul>
    )
}

That way, you will only display the select user in you <ul> .这样,您将只在<ul>中显示 select 用户。 To unselect your user, just call setID(null)要取消选择您的用户,只需调用setID(null)

Show user profile instead of list显示用户个人资料而不是列表

If that solution work to filter your list, I guess you might want to adapt your page to show all details from your user.如果该解决方案可以过滤您的列表,我想您可能希望调整您的页面以显示用户的所有详细信息。 Next step would be to implement multi pages using react-router-dom with a url container your user uuid.下一步是使用react-router-dom和 url 容器您的用户 uuid 来实现多页面。

You can look at the url-params example which might be exactly what you are looking for.您可以查看可能正是您正在寻找的url-params 示例

Here's a slightly detailed option that extends beyond a single component but more easy to scale on account of modularity.这是一个稍微详细的选项,它超越了单个组件,但由于模块化而更容易扩展。

Create a new react component in a new file say, UserDetails.js在一个新文件中创建一个新的反应组件,比如UserDetails.js

Now you need a way to navigate to this new page when the button is clicked.现在,您需要一种在单击按钮时导航到这个新页面的方法。 So in your App.js you need a router like所以在你的App.js中你需要一个像

import { BrowserRouter, Switch} from 'react-router-dom'

Then in your App.js file wrap all your components in the router:然后在您的 App.js 文件中将所有组件包装在路由器中:

class App extends Component {
    render() {
        return (
      <BrowserRouter>
          <div className="App">
             <Switch>
            <Route exact path="/user-list" component={UserList} />
            <Route exact path="/detail" component={UserDetails}/>
            </Switch>
          </div>
    </BrowserRouter>
   );
  }
}
export default App;

Now you are ready to navigate to the user details page, when the button is clicked.现在,当单击按钮时,您已准备好导航到用户详细信息页面。 So add a function like goToDetails like:所以添加一个 function 就像goToDetails一样:

 <button onClick={() => goToDetails(item)}>

Next define the function that navigates to the next page接下来定义导航到下一页的 function

goToDetails(item) {
  this.props.history.push('/detail', {selectedUser:item:});
}

The history prop is available above because we earlier wrapped the entire app in BrowserRouter . history 属性在上面可用,因为我们之前将整个应用程序包装在BrowserRouter中。

In the details page, you get the selectedUser details as a prop:在详细信息页面中,您将获得selectedUser详细信息作为道具:

const selectedUser = this.props.location.state.selectedUser;

Now you can render it however you want.现在你可以随心所欲地渲染它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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