TypeError: Cannot read property of null in React Component

TypeError: Cannot read property of null in React Component

我有一个 React-Select 组件,它呈现一个下拉菜单,当从下拉菜单中选择一个项目时,将呈现一个按钮。

import React, { Component } from 'react';
import Select from 'react-select';
class selectDemo extends Component {
state = { 
    selectedOption: '',
    data: [
        {Model: 'Option1'},
        {Model: 'Option2'},
    ],
 }

//Handler for Select Drop Down
handleChange = (selectedOption) => {
    this.setState({selectedOption}, ()=>console.log(this.state.selectedOption.Model));
}

RenderButton = () => {           
        return <button type="button" className="btn btn-primary">{this.state.selectedOption.Model}</button>
}

render() {
    console.log(this.state.selectedOption);
    const { selectedOption } = this.state;
    const value = selectedOption && selectedOption.Model;
    return (
        <div>
            <div name="selectedOption" className="section">
                <Select
                    className='form-control'
                    placeholder='Select Option'
                    name="selectedOption"
                    value={value}
                    onChange={this.handleChange}
                    labelKey='Model'
                    valueKey='Model'
                    optionClassName='dropdown-item'
                    options={this.state.data}
                />
            </div>
            <div className="section">
               {this.state.selectedOption.Model && <this.RenderButton/>}
            </div>
        </div>
    );
}
}
export default selectDemo;

但是,如果我清除该值,即不选择另一个,而是单击 x 删除我的选择,我得到一个

TypeError: Cannot read property 'Model' of null

错误正好在第 54 行,我实际上正在检查该值是 'null' 还是 'undefined'。我在阅读后尝试使用 typeofifswitch 语句:

但这也行不通。

您需要做的是在访问 Model 之前提供检查,因为当您取消选择一个选项时,selectedOption 变为空并且您无法从中访问 属性。

 <div className="section">
       {this.state.selectedOption && this.state.selectedOption.Model && <this.RenderButton/>}
 </div>

错误似乎源自您的线路:

{this.state.selectedOption.Model && <this.RenderButton/>}

如果 selectedOption 具有真值,这将起作用。但是,如果具有 null 的值,则从中读取 Model 是没有意义的。因此,您需要先检查 selectedOption 是否真实,然后再检查 Model.

您已经在 render() 方法的顶部这样做了:

const value = selectedOption && selectedOption.Model;

所以你可以这样做:

{value && <this.RenderButton/>}

或者,这里有一个解决这个问题的巧妙方法,特别是如果 属性 有很多层次:

(selectedOption || {}).Modal && <this.RenderButton/>

这意味着如果 selectedOption 是假的你可以创建一个临时对象 {} 这样你 可以 尝试读取 Modal它没有收到错误。