反应渲染变量undefined

问题描述 投票:-2回答:3

由于某些原因,我不明白,我似乎无法在我的渲染器中获取状态值,起初我认为这是一个范围问题,但即使更改为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>               
            );
        }

enter image description here

为什么我的Object数组值在渲染器中未定义?

注意:屏幕截图中的两个const变量都更改为var,并且行为仍然存在。

reactjs renderer
3个回答
0
投票

你需要在你的班级或state里面定义constructor()

constructor(props) {
  super(props);

  this.state = {
    project: // something
  }
}

componentDidMount() { 
  // etc.

0
投票

你的例子并不清楚你想要实现什么,但可能是以下原因之一:

  • 在你的componentDidUpdate你在this.getatuff有一个错字(我假设你试图说getStuff
  • project似乎是在你的渲染器上定义的,你的截图显示它有一个密钥id:5和其他一些,但它可能没有密钥bodybody可能不是一个数组,或者数组可能只包含1个值[0]而不是两个价值[0][1]。我建议你调试project的结构以获得正确的值

0
投票

你在这里得到语法错误: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>               
        );
    }
© www.soinside.com 2019 - 2024. All rights reserved.