反应:如何根据"If"语句启用按钮



我的论坛页面上有一个按钮,除非你以MongoDB中定义的管理员身份登录,否则我希望禁用它。(在Mongo中,我有一个角色文档,对于特定用户显示为"admin"(

将在下面提供一些代码:

constructor(props) {
super(props);
this.state = {
questions: [], // used to store questions from API call
answers: [], // used to store all answers stored in database
filteredAnswers: [], // used to store the filtered answers for a given question
displayAnswers: false, // used to display the answer modal or not
disabled: true,
role: null,
};
}
handleClickPostAnswer(questionID, questionText) {
const answerInput = window.prompt(`Please enter your answer to Question ${questionID}: ${questionText}`, 'Enter answer here');
if (answerInput === null) {
console.log('No answer posted');
return;
}
else if (this.state.role == 'admin') {
console.log('User is an Admin');
this.setState({
disabled: false,
})
}

// ADD ACTUAL USERNAME HERE
this.postAnswer(questionID, answerInput, 'John');
console.log(`Posted answer: ${answerInput}`);
}
componentDidMount() {
axios.get('/getquestions')
.then((response) => {
console.log(response.data);
this.setState({questions: response.data});
});
}
<tbody>
{/* within the table, take array  */}
{this.state.questions.map((question) => {
return (
<tr key = {question._id}>
<td>{question._id}</td>
<td>{question.questionText}</td>
<td>{question.username}</td>
<td>{question.labels}</td>
<td><Button disabled={this.state.disabled} onClick={() => this.handleClickPostAnswer(question._id, question.questionText)}>Answer</Button></td>
<td><Button onClick={() => this.handleClickReadAnswers(question._id)}>Display</Button></td>
</tr>
);
})}
</tbody>

目前,该按钮似乎一直被禁用,即使我是作为具有";管理员";Mongo中附加到它们的字段。可能错过了一些简单的东西,但不确定为什么这不会奏效。

它在MongoDB 中的外观

谢谢!

在哪个功能中将角色设置为admin?

您可以检查角色并相应地禁用它。

<Button 
disabled={this.state.role !== 'admin'} 
/>

看起来你从来没有在状态中设置角色,下面是代码ever-logs"'用户是管理员";似乎没有

else if (this.state.role == 'admin') {
console.log('User is an Admin');
this.setState({
disabled: false,
})
}

在状态中设置角色,应该有助于

最新更新