由于某些原因,我不明白,我似乎无法在我的渲染器中获取状态值,起初我认为这是一个范围问题,但即使更改为var后,我的变量是未定义的。
constructor(props) {
super(props);
this.state = {
stuff: {}
};
componentDidMount(){
this.getatuff.then( (result) =>{
this.setState({
stuff: result.items[0]
});
});
console.log('REACT Coveo component DOM loaded');
}
render() {
var ReactMarkdown = require('react-markdown');
var project = this.state.stuff;
debugger;
if(!Object.entries(project).length === 0){
var asd = project.body[1].value; <---UNDEFINED
return (
<div className="block">
<ReactMarkdown source={asd} />
</div>
);
}
为什么我的Object数组值在渲染器中未定义?
注意:屏幕截图中的两个const变量都更改为var,并且行为仍然存在。
你需要在你的班级或state
里面定义constructor()
:
constructor(props) {
super(props);
this.state = {
project: // something
}
}
componentDidMount() {
// etc.
你的例子并不清楚你想要实现什么,但可能是以下原因之一:
componentDidUpdate
你在this.getatuff
有一个错字(我假设你试图说getStuff
project
似乎是在你的渲染器上定义的,你的截图显示它有一个密钥id:5
和其他一些,但它可能没有密钥body
或body
可能不是一个数组,或者数组可能只包含1个值[0]
而不是两个价值[0]
和[1]
。我建议你调试project
的结构以获得正确的值你在这里得到语法错误:if(!Object.entries(project).length === 0)
它应该是if (!(Object.entries(project).length === 0))
render() {
var ReactMarkdown = require('react-markdown');
var project = this.state.stuff;
debugger;
if (!(Object.entries(project).length === 0)) {
var asd = project.body[1].value; <---UNDEFINED
return (
<div className="block">
<ReactMarkdown source={asd} />
</div>
);
}