为什么:无法读取null的getBoundingClientRect属性?

时间:2018-07-15 19:47:11

标签: javascript reactjs

这是我见过的最令人惊讶的事情。考虑以下代码:

getElementDims = (elem, task) => {
        this.setState( prevState => {
            const taskDims = {...prevState.taskDims};
            taskDims[task.id] = true;
            taskDims[task.id] = elem.getBoundingClientRect();
            //the error occured from the above line of code
            return {taskDims}
        })
        
        console.log(elem.getBoundingClientRect())
        //if the setState() is commented out, logs the right values without error
    }
    taskRows = () => {
        const {display, directTasks, tasks, rootParent} = this.state;
        return directTasks[display]
        .filter(directTask => directTask.rootParent === rootParent)
        .map(directTask => {
            const childTasks = () => {
                return tasks[display]
                .filter(task => task.biggestParentInDisplay === directTask.biggestParentInDisplay)
                .map(task => {
                    return <div className = 'task' style={{
                        gridColumn: `${task.colStart - directTask.colStart + 1 } / span ${length(task)}`,
                        gridRowStart: task.level + ' / span 1',
                        backgroundColor: `rgba(42, ${255 - (55 / task.level) }, 139, 0.76)`,
                        gridTemplateColumns: `repeat(${length(task)}, 1fr)`,
                    }}>
                        {progress(task)}
                        <p className='tlTaskName'>{task.name}</p>
                    </div>
                })
            }

            const onDown = (e, task) => {
                this.isDragging = true;
                this.setState({
                    gridUnit: length(task) / this.state.taskDims[task.id].width,
                })
                console.log(e.pageX, this.state.taskDims[task.id].left)
            }
            return <div 
                className = 'directTask' 
                style = {{
                    gridColumn: `${this.state.dragX || directTask.colStart + 1} / span ${length(directTask)}`,
                    gridTemplateColumns: `repeat( ${length(directTask)} , 1fr)`,
                    gridTemplateRows: "repeat(" + directTask.rows + ", 1fr)"
                }}
                ref={e => this.getElementDims(e, directTask)}
                onPointerDown={e => onDown(e, directTask)}
            >
                {childTasks()}
            </div>
        })
    }
            
    render(){
        return(
            <div className = 'timeline' style={{
                display: "grid",
                gridTemplateColumns: "auto [start] 1fr",
                gridTemplateRows: "100px repeat(" + this.state.rows + ", 150px)",
            }} >
                {this.tasksRows()}
            </div>
         )
    }

我唯一的问题是:为什么?我的意思是,如果我在setState内读取属性,则为空,如果在console.log中读取,则不为空是可能的。我不知道从代码中解决问题有什么意义,请让我知道是否缺少重要的内容。

0 个答案:

没有答案