首页 > 解决方案 > ReactJS - 如何访问函数内的状态值?

问题描述

我有 reactjs 组件:

import React, { Component, actions } from 'react';
import { connect } from "react-redux";


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

    this.state = {
      ObtenerdataETH: [],
      ObtenerdataBTC: [],
      ObtenerdataXRP: [],
    };

  }

  render() {

    function DevuelveValorCrypto(testing) {
      console.log("check received: ", testing)
      const TipoCrypto = testing;

      let test123 = this.state.ObtenerdataETH.price
      console.log("check received: valor de test123", test123)

      return (
        <DIV>bla bla </DIV>
      );
    }
    ...
  }
}
const mapStateToProps = state => {
  return {
    token: state.token,
    //selectvalue: state.value

  };
};

//Dispaching to STORE:
const mapDispatchToProps = (dispatch) => {
  return {
    onSelectCrypto: (value) => dispatch(actions.SelectCrypto(value))
  }
};

export default connect(mapStateToProps, mapDispatchToProps)(CardTradeSim);

我收到了一些this.state这样的属性:this.state.ObtenerdataETH并且正在完美地工作。

但是当我需要在一个函数中时,我有这个错误:

TypeError: Cannot read property 'state' of undefined

如何在函数中使用它?

标签: javascriptreactjsstate

解决方案


正如 Neil 在评论中提到的,您必须使用箭头函数而不是命名,因为箭头函数没有范围:

import React, { Component, actions } from "react";
import { connect } from "react-redux";

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

    this.state = {
      ObtenerdataETH: [],
      ObtenerdataBTC: [],
      ObtenerdataXRP: [],
    };
  }

  // Arrow function
  DevuelveValorCrypto = (testing) => {
    console.log("check received: ", testing);
    const TipoCrypto = testing;

    let test123 = this.state.ObtenerdataETH.price;
    console.log("check received: valor de test123", test123);

    return <DIV>bla bla </DIV>;
  };

  render() {
    <DevuelveValorCrypto testing="..." />;
  }
}

const mapStateToProps = (state) => {
  return {
    token: state.token,
    //selectvalue: state.value
  };
};

//Dispaching to STORE:
const mapDispatchToProps = (dispatch) => {
  return {
    onSelectCrypto: (value) => dispatch(actions.SelectCrypto(value)),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(CardTradeSim);

推荐阅读