如何修复“未捕获的类型错误:无法读取 null 的属性‘value’”错误?
2017-04-13
1746
我想在 React 中设置一个简单的购物车。我试图制作一个带有服装尺码的下拉菜单。我在渲染中设置了它,但出现了错误,我得到了:
Uncaught TypeError: Cannot read property 'value' of null
。
这是我的 JSX:
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>
);
}
}
我的渲染返回了 Null 值,这有什么问题吗?
编辑
由于这是由于 Null 值导致的,我该如何修复它以获取下拉菜单?
2个回答
原因是,您没有定义
constructor
和
state
变量,并且您正在访问
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>
);
}
}
Mayank Shukla
2017-04-13
select
元素正在请求
this.state.value
。看来
this.state
为
null
,因此您在尝试访问
null.value
时会看到该错误。
CynicalBusiness
2017-04-13