如何修复"未捕获TypeError:无法读取属性'值' of null"错误?

时间:2017-04-13 03:59:49

标签: javascript reactjs webpack

我想在React中设置一个简单的购物车。我试图提供一个尺码为服装项目的下拉菜单。我在渲染中进行了设置,但出现了问题,我得到了:import React, { Component } from 'react'; let cart = {price:0,item:"",size:""} export default class Cart extends Component { handleClick(){ e => { cart = {price:0,item:"userselection",size:"userselection"}; } console.log(cart); } itemSelection(){ let userOrder = {price:0,item:"",size:""}; let userItem = ""; if (userItem == "pants1") { let itemPrice = 20.00; } } render() { return ( <div className='Webshop' id='Webshop'> <li> <img src="./gods.jpeg" width="350" height="350"></img> <button onClick={this.handleClick} id="addit">Add to cart</button> <select id="size" onChange={this.change} value={this.state.value}> <option value="medium">Medium</option> <option value="large">Large</option> <option value="x-large">X-large</option> </select> <img src="./gods.jpeg" width="350" height="350"></img> </li> </div> ); } }

这是我的JSX:

new SigninActivity(username, password).execute();

我的渲染器返回Null值是否有问题?

修改

由于这是由Null值引起的,我如何解决此问题以获取下拉菜单?

2 个答案:

答案 0 :(得分:2)

原因是,您没有定义constructorstate变量,而您正在访问this.state.value。首先像这样定义state

constructor(){
   super();
   this.state = {value: ''}
}

您使用arrow function的方式错误,请按照以下方式使用:

handleClick = (e) => {
   cart = {price:0,item:"userselection",size:"userselection"};
   console.log(cart);
} 

您没有定义change方法,也定义了它。

像这样编写你的组件:

export default class Cart extends Component {
    constructor(){
        super();
        this.state = {value: ''}
        this.handleClick = this.handleClick.bind(this);
        this.change = this.change.bind(this);
    }

    handleClick() {
        cart = {price:0,item:"userselection",size:"userselection"};
        console.log(cart);
    } 

    change(e){
        this.setState({value: e.target.value})
    }

    itemSelection(){
        let userOrder = {price:0,item:"",size:""};
        let userItem = "";
        if (userItem == "pants1") {
           let itemPrice = 20.00;
        }
    }


    render() {
        return (
            <div className='Webshop' id='Webshop'>
                <li>
                    <img src="./gods.jpeg" width="350" height="350"></img>
                    <button onClick={this.handleClick} id="addit">Add to cart</button>
                    <select id="size" onChange={this.change} value={this.state.value}>
                        <option value="medium">Medium</option>
                        <option value="large">Large</option>
                        <option value="x-large">X-large</option>
                    </select>
                    <img src="./gods.jpeg" width="350" height="350"></img>
                </li>
            </div>
        );
    }
}

答案 1 :(得分:0)

select元素正在请求this.state.value。似乎this.statenull,因此您在尝试访问null.value时会看到该错误。