javascript - 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
如何在函数中使用它?
解决方案
正如 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);
推荐阅读
- javascript - Onclick 事件打开一个新页面并通过使用 javascript 执行 api 调用来加载表
- javascript - 在 Object 的情况下,Javascript 重新分配和引用如何工作?需要深入解释吗?
- html - How can I get my AdRotator ads to stay within the div?
- python - 按数字顺序对文件进行排序,同时排除具有非数字文件名的文件
- swift - 我不小心隐藏了更改并将我的 Xcode 项目恢复到旧版本。如何将其还原为我隐藏的更改?
- javascript - 为什么我无法更新我的反应组件的状态?
- d3.js - 我怎样才能给这个径向集群直线而不是曲线?
- python - JupyterNotebook:属性错误:'NoneType' 对象没有属性'lower'
- c# - 使用 Perfview 查找调用次数最多的方法
- docker - 为多服务项目(单域)设置 SSL 证书