【问题标题】:in react i want to select only one user my code is selecting every user在反应中我只想选择一个用户我的代码正在选择每个用户
【发布时间】:2021-02-27 06:19:58
【问题描述】:

当我单击添加朋友按钮时,我面临一个问题,每个按钮都会更改为请求我如何才能将其特别设置为仅我单击的一个用户我尝试了一些事情但它不起作用它正在选择所有其他用户。我使用了handleproductselect 功能,但它不起作用我给了他们单独的ID,但它仍然不起作用

class SearchModal extends Component {
  constructor(props){
    super(props);
    this.state = {
        Input:"Add Friend",
        backgroundColor: 'white',
        active_id: null,
    }
}

async handleProductSelect(elementid){
  const id = elementid;
  const { backgroundColor } = this.state;
  let newBackgroundColour = backgroundColor === 'white' ? 'yellow' : 'white';
  this.setState({ 
    Input : "Requested",
    backgroundColor: newBackgroundColour,
    active_id: id
  })
  console.log(id)
}

render() {
    const {currentUser} = this.props;
    return (
       <div>
          <Modal show={this.state.show} onHide={this.handleClose} 
          >
             <Modal.Header closeButton>
               <Modal.Title>
                 <input 
                  type="text" 
                  placeholder="Search.."
                  value={search}
                  onChange={this.onTextboxChangeSearch}
                 ></input>
               </Modal.Title>
             </Modal.Header>
             <Modal.Body>
               <h3>Users</h3>
               <div>
                <ul className="collection">
                  {userdetails.map((element) => {
                    if(currentUser.user.username !== element.username){
                      return(
                        <div key={element._id}>
                          <li>{element.username}{' '}<input 
                          type="button" 
                          id={element._id} 
                          onClick={this.handleProductSelect.bind(this,element._id )} 
                          value={this.state.Input} 
                          style = {{backgroundColor: ( element._id === this.state.active_id ?  'yellow' : this.state.backgroundColor)}}></input></li>
                        </div>
                      );
                    }else{
                      return(
                        <div key={element._id}>
                          <li>{element.username}</li>
                        </div>
                      );
                    }
                  })}
                </ul>
               </div>
             </Modal.Body>
          </Modal>
        </div>
    )
  }
}

【问题讨论】:

    标签: reactjs select button compiler-errors mern


    【解决方案1】:

    问题

    您已正确使用状态来存储“活动 id”,但您仅使用单个状态来表示按钮的值。

    <input 
      type="button" 
      id={element._id} 
      onClick={this.handleProductSelect.bind(this, element._id)} 
      value={this.state.Input} // <-- same single state for all buttons!
      style = {{
        backgroundColor: (element._id === this.state.active_id ?  'yellow' : this.state.backgroundColor)
      }}
    />
    

    解决方案

    由于我认为目的是保留已“激活”的按钮,即您希望保留“已请求”标签,因此您应该添加一些状态来存储所有请求的活动 ID。也不需要将静态内容存储为按钮标签的状态,与背景颜色相同,这都是基于state.active_id值的派生数据。

    this.state = {
      active_id: null,
      requestedIds: {},
    }
    

    handleProductSelect 更新为柯里化箭头函数。箭头函数将类组件的this 绑定到回调。 curried 函数允许您不需要匿名回调函数来附加处理程序

    handleProductSelect = id => () => {
      this.setState(prevState => ({ 
        active_id: prevState.active_id === id ? null : id, // toggle active id
        requestedIds: {
          ...prevState.requestedIds,
          [id]: id, // add requested id
        },
      }));
    }
    

    更新Input 以检查requestedIds 是否具有当前元素_id 的键,并有条件地呈现按钮标签。同样,检查背景颜色的活动 id。

    <input 
      type="button" 
      id={element._id} 
      onClick={this.handleProductSelect(element._id)} 
      value={this.state.requestedIds[element._id] ? 'Requested' : 'Add Friend'}
      style = {{
        backgroundColor: (element._id === this.state.active_id ?  'yellow' : 'white')
      }}
    />
    

    【讨论】:

    • 你好@DrewReese 我在上面的代码中遇到了一个问题我应该做些什么改变来在两个朋友列表中添加朋友ID,比如接收者和用户
    • @PratikZinjurde 我认为您可能需要围绕这个新问题提供更多背景信息。如果您可以为您正在尝试做的事情创建一个正在运行的代码框,我不介意有时间看一看。这似乎也是一个新问题。不过,发布一个新的 SO 问题可能会更快,你会得到更多的关注。如果您这样做,请随时在我这里提供链接。
    • 好的,谢谢,但我做到了,现在它的工作让 user = await User.findByIdAndUpdate( id,{ $push: {"friendsList" : {friendId:fid}} } ) if (user){ await User.findByIdAndUpdate(fid,{ $push: {"friendsList" : {friendId:id}} } )// 我添加了这一行,现在在两个用户的朋友列表中,彼此的 id 都被添加 res.status(200)。 json({ message:"用户找到", user, });实际上我是在问如何连接两个用户,比如用户 id 是我们向其发送请求的另一个朋友 id,这实际上就像一个黑客攻击
    • 你好@DrewReese当我刷新按钮的值时我需要你的帮助重置如何使其永久化我正在考虑使用localstorage但我没有找到将localstorage的条件放在哪里如果friendsid = userid然后它将始终显示按钮的消息值
    • @PratikZinjurde 当然。一个常见的解决方案是使用 localStorage 来持久化您的应用程序状态。您使用componentDidUpdate 将组件状态持久化到本地存储,并使用componentDidMount 读取并初始化您的组件状态。
    猜你喜欢
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    • 2021-10-09
    • 1970-01-01
    • 2017-07-31
    相关资源
    最近更新 更多