首页 > 解决方案 > 选择反应 POST

  • 物品编号
  • 问题描述

    我想获取点击<li>项目的 ID 并使用 Fetch 发布这个值。我不知道如何处理它。我在等你的帮助。

    我在这张照片上解释了我的代码。基本上我可以列出项目内的所有用户列表<li>。有用!但我需要获取单击项目的“user.id”并保存到“setClickedUser”之类的状态。然后使用 Fetch 发布此 ID。

    描述

    const [username, setUsername] = useState([]);
    const [conversatid, setConversatId] = useState([]);
    
    useEffect(()=>{
        
      fetch('http://localhost:8000/api/current_user/', {
        headers: {
          Authorization: `JWT ${localStorage.getItem('token')}`
        }
      })
        .then(res => res.json())
        .then(json => {
          setUsername(json.id);
        });
    
    },[]) 
    
    const convcreate = (e, data, kullanici) => {
    
      fetch('http://localhost:8000/api/conversat/', {
        method: 'POST',
        headers: {
          Authorization: `JWT ${localStorage.getItem('token')}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({User1i: username, User2ii: clickeduser,})
      })
        .then(res => res.json())
        .then(json => {
          setConversatId(json.id);
        }); };
    
      const alluClicked = user => evt => {
    
        /// GET CLICKED USER'S ID AND SAVE INTO "clickeduser"
    
      }
    
        return (
            <div className="kullist">
                    { props.allusers2 && props.allusers22.map( user => {
                    return (
    
                        <li key={user.id} onClick={alluClicked} className="tumtekkul">
    
      
                                    <a> {user.username} </a>
    
    
                        </li> );  })} </div> ) }
    

    标签: javascriptreactjsreact-hooks

    解决方案


    你可以这样做:

    const alluClicked = userId => {
      // SAVE userId where you need
    }
    
    return (
      <div className="kullist">
      {props.allusers2 && props.allusers22.map(user => {
        return (
          <li key={user.id} onClick={() => alluClicked(user.id)} className="tumtekkul">
    

    推荐阅读