React三元运算符能否实现多条件判断?论坛回复删除Bug修复咨询
Absolutely, this requirement is completely feasible! You just need to combine two conditions in your ternary operator—verifying both that the user is logged in and their ID matches the reply's author ID. Here's how to implement it smoothly:
Step 1: Update the Visibility Condition in Your Render Method
In your repliesData map function, replace the single ID check with a combined condition using the logical AND (&&) operator. This ensures both criteria must be met for the delete icon to appear:
// Replace this existing condition: {this.state.userId == row.reply_user_id ? <i className="far fa-trash-alt" onClick={this.deleteReply.bind(this, row.reply_id)} title="Delete this reply?"></i> : null } // With this combined check: {this.state.isLoggedin && this.state.userId === row.reply_user_id ? <i className="far fa-trash-alt" onClick={this.deleteReply.bind(this, row.reply_id)} title="Delete this reply?"></i> : null }
Quick note: I switched to strict equality (===) instead of loose equality (==)—this is a JavaScript best practice to avoid unexpected bugs from implicit type conversion.
Step 2: Add Critical Backend Validation (Don’t Skip This!)
While the frontend check hides the delete button from unauthorized users, it’s not enough to secure your app. Malicious users could manipulate frontend code or send direct API requests to delete replies they don’t own.
Make sure your deleteReply endpoint (in ForumpageService or your backend logic) also:
- Confirms the user is actually logged in (via valid auth tokens or session data)
- Verifies the logged-in user’s ID matches the
reply_user_idof the target reply
This adds a non-negotiable layer of security to prevent unauthorized deletions.
Full Modified Render Section Snippet
Here’s how the relevant part of your render method will look after the change:
render(){ const repliesData = currentReply.map((row, index) => { return ( <div className="reply-container" key={index}> {row.reply_status == 0 ? <div className="row" id="reply-messages-deleted"> <div className="col-md-8"> <p>{row.userName}</p> <p>{row.reply_message}</p> <p>This reply has been deleted</p> </div> <div className="col-md-2"> {this.state.isLoggedin && this.state.userId === row.reply_user_id ? <i className="far fa-trash-alt" onClick={this.deleteReply.bind(this, row.reply_id)} title="Delete this reply?"></i> : null } </div> </div> : <div className="row" id="reply-messages" key={index}> <div className="col-md-8"> <p>{row.userName}</p> <p>{row.reply_message}</p> </div> <div className="col-md-2"> {this.state.isLoggedin && this.state.userId === row.reply_user_id ? <i className="far fa-trash-alt" onClick={this.deleteReply.bind(this, row.reply_id)} title="Delete this reply?"></i> : null } </div> </div> } </div> ) }) // Rest of your render code... }
That’s all! Now the delete icon will only show up when the user is logged in and they’re the original author of the reply.
内容的提问来源于stack exchange,提问作者Curious13

