【发布时间】:2023-04-01 17:21:01
【问题描述】:
我有一个组件,我正在尝试为其创建一个状态。可以成功记录/警告此状态,但在我的 return 语句中使用时它不起作用。
这里是组件。不起作用的状态是 viewMoreToken。这是在 map 函数中使用的。
class DisplayWSAAnsweredQuestions extends React.Component {
constructor(props) {
super(props);
this.state = {
viewMoreToken: false
};
}
render() {
alert(this.state.viewMoreToken);
return (
<>
{this.props.answeredQuestions &&
this.props.answeredQuestions.map(function(question, index) {
if (!this.state.viewMoreToken) {
if (
question.QuestionResponse === "Y" ||
question.QuestionResponse === "N"
) {
return (
<>
<div
style={{
backgroundColor: "#E6E6E6",
padding: "1px"
}}
>
<ul>
{" "}
<b> Q :</b>
<div style={{ float: "right" }}>✔️</div>
{question.QuestionWhenAnswered}
</ul>
</div>
</>
);
} else if (question.QuestionResponse === "P") {
return (
<>
<div
style={{
backgroundColor: "#BDBDBD",
padding: "1px"
}}
>
<ul>
<b> Q :</b>
{question.QuestionWhenAnswered}{" "}
<div style={{ float: "right" }}>❌</div>
{/* <br />
<b> S :</b>
{question.SuggestedSoloution} */}
</ul>
</div>
</>
);
}
} else {
return <>Nice </>;
}
})}
</>
);
}
}
这是错误消息。
TypeError: Cannot read property 'state' of undefined
为什么在使用警报时它显示它被设置为 false 很好,但是一旦在 .map 函数的 if 语句中使用它,它就会说它是未定义的。
非常感谢任何建议。
【问题讨论】:
-
你能像这样碰巧
map。this.props.answeredQuestions.map((question, index) => {bla bla bla}) -
什么意思?
-
哦,我看到将其更改为箭头功能。这就是我使用 sv12 answer 解决这个问题的方法。谢谢!
-
这是因为
this未绑定到正确的上下文,因为您使用的是function(question, index)而不是arrow functions,如(question, index) => {...}。您可以在JavaScript- hackernoon.com/… 中阅读有关this工作原理的更多信息 -
是的,我的意思是箭头函数。请投票。
标签: javascript reactjs