【发布时间】:2020-09-25 07:26:43
【问题描述】:
我的论坛页面上有一个按钮,除非您以 MongoDB 中定义的管理员身份登录,否则我希望禁用该按钮。 (在 Mongo 中,我有一个角色文档,对特定用户显示为“管理员”)
下面会提供一些代码:
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 中附加了“admin”字段的用户身份登录,该按钮似乎一直处于禁用状态。可能遗漏了一些简单的东西,但不确定为什么这不起作用。
谢谢!
【问题讨论】: