加载中...
  • TypeError: Cannot read property 'state' of undefined

    问题描述:

    react组件中的方法获取state中的值时报错:TypeError: Cannot read property ‘state’ of undefined

    解决办法:

    方法一(在constructor中绑定this到函数):this.funOne = this.funOne.bind(this);

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    import React , {Component} from 'react'; 

    class Home extends Component {
    constructor(props){
    super(props);

    this.state = {
    one: 'one'
    }

    this.funOne = this.funOne.bind(this); // 主要是这一行绑定this到函数funOne
    }

    funOne () {
    alert(this.state.one)
    }

    render () {
    return (
    <div className="Home">
    <button onClick={this.funOne}>funOne</button>
    </div>
    );
    }
    }

    export default Home;

    方法二(使用箭头函数):funOne = () => {}

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    import React , {Component} from 'react'; 

    class Home extends Component {
    constructor(props){
    super(props);

    this.state = {
    one: 'one'
    }
    }

    funOne = () => {
    alert(this.state.one)
    }

    render () {
    return (
    <div className="Home">
    <button onClick={this.funOne}>funOne</button>
    </div>
    );
    }
    }

    export default Home;

    方法三(绑定方法的同时绑定this):onClick={this.funOne.bind(this)}

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    import React , {Component} from 'react'; 

    class Home extends Component {
    constructor(props){
    super(props);

    this.state = {
    one: 'one'
    }
    }

    funOne () {
    alert(this.state.one)
    }

    render () {
    return (
    <div className="Home">
    <button onClick={this.funOne.bind(this)}>funOne</button>
    </div>
    );
    }
    }

    export default Home;

    上一篇:
    umi 配置多环境编译打包
    下一篇:
    antd报错Warning: Instance created by `useForm` is not connected to any Form element
    本文目录
    本文目录