为什么点击按钮会出现这个错误?我的onClick={this.handleChange}哪里写错了
Cannot read property 'setState' of undefined
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import Picker from '../components/Picker.js';
import {
//selectSubreddit,
//fetchPostsIfNeeded,
//invalidateSubreddit
} from '../actions'
// onClick={this.handleChange}
class AsyncApp extends Component {
constructor(props) {
super(props);
this.state={
figure: "清华我的梦"
}
}
componentDidMount() { // 渲染完成之后调用一次
}
componentDidUpdate(prevProps) { // 初始化渲染不会调用,更新前调用
console.log(this.state.figure);
}
handleChange(nextSubreddit) {
// this.props.dispatch(selectSubreddit(nextSubreddit))
// this.props.dispatch(fetchPostsIfNeeded(nextSubreddit))
this.setState({figure: '谁信啊'});
}
/*
handleClick(event) {
this.setState({figure: '谁信啊'});
}
render() {
let v = this.state.figure;
return (
<div>
<Picker
value={v}
onClick={this.handleClick.bind(this)}
/>
</div>
)
}
*/
render() {
let v = this.state.figure;
return (
<div>
<Picker
value={v}
onClick={this.handleChange}
/>
</div>
)
}
}
/*
*/
export default AsyncApp
import React, { Component } from 'react'
import PropTypes from 'prop-types'
// <button onClick={()=>{this.doubleNumber()}}>我的人生了567</button>
export default class Picker extends Component {
constructor(){
super();
this.state={
origin:true
}
}
doubleNumber(){
this.setState({
origin:!this.state.origin
});
}
render() {
const { value, onClick } = this.props
// var value = this.props.value;
let number = 5;
if(!this.state.origin){
number*=2;
}else{
number = 5;
}
return (
<div>
<h1>{value}</h1>
<button onClick={e => onClick(e.target.value)}>我的人生了567</button>
<h2>{number}</h2>
</div>
)
}
}
Picker.propTypes = {
value: PropTypes.string.isRequired
}
两种方法,一个是使用 bind,另一种是使用 箭头函数
使用bind
修改 Picker 组件如下
使用箭头函数
箭头函数是es6新增的特性,你的代码修改下 handleChange 就可以了