渲染后如何访问特定的 array.map 项目?

How can I access a specefic array.map item after render?

在我的应用程序中,如果用户请求收养宠物,我会呈现一个确认按钮。我如何启用确认按钮来访问它所呈现的用户的 ID?

import React, { useEffect, useState } from "react";
import { BACK_PORT } from "../../var";
import axios from "axios";
import { Button } from "react-bootstrap";

function UsersDashboard() {
  const [users, setUsers] = useState([]);
  const token = localStorage.getItem("auth-token");
  useEffect(() => {
    axios
      .get(`${BACK_PORT}/data/users`, { headers: { "auth-token": token } })
      .then(function (response) {
        setUsers(response.data);
      })
      .catch(function (error) {
      });
  }, [token]);

  const onConfirm = () => {
    //Send ID of user
  };

    return users.map((item) => (
    <div key={item._id}>
      <div>Username: {item.name}</div>
      {item.adoptionRequest && (
        <div>Adoption Request: {item?.adoptionRequest}</div>
      )}
      {item.adoptionRequest && (
        <div>
          <Button onClick={onConfirm}>Confirm</Button>
        </div>
      )}
      {item.adoptionRequest && <div>hello</div>}
    </div>
  ));
}

export default UsersDashboard;

替换

onClick={onConfirm}

onClick={() => onConfirm(item._id)}
import React, { useEffect, useState } from "react";
import { BACK_PORT } from "../../var";
import axios from "axios";
import { Button } from "react-bootstrap";

function UsersDashboard() {
  const [users, setUsers] = useState([]);
  const token = localStorage.getItem("auth-token");
  useEffect(() => {
    axios
        .get(`${BACK_PORT}/data/users`, { headers: { "auth-token": token } })
        .then(function (response) {
          setUsers(response.data);
        })
        .catch(function (error) {
        });
  }, [token]);

  const  onConfirm = (userId) => {
    console.log(userId)
    //Send ID of user
  };

  return users.map((item) => (
      <div key={item._id}>
        <div>Username: {item.name}</div>
        {item.adoptionRequest && (
            <div>Adoption Request: {item?.adoptionRequest}</div>
        )}
        {item.adoptionRequest && (
            <div>
              <Button onClick={() => onConfirm(item._id)}>Confirm</Button>
            </div>
        )}
        {item.adoptionRequest && <div>hello</div>}
      </div>
  ));
}

export default UsersDashboard;

我很困惑,因为按钮总是“启用”的,因此可以点击。

我猜你想在用户未请求收养时禁用该按钮?

如果是这种情况,只需使用标签的 disabled attribute

const onConfirm = (userId) => {
axios.get(`data/user/${userId}`);
//Send ID of user by accessing userId
};
<Button disabled={item.adoptionRequest === null} onClick={() => onConfirm(item._id)}>Confirm</Button>