[英]ReactJS - How to get access to state value inside a funciton?
我有 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
如何在 function 中使用它?
正如 Neil 在评论中提到的,您必须使用箭头函数而不是命名,因为箭头 function 没有 scope:
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);
会推荐使用函数式编程。
import React, { useState } from 'react';
const CardTradeSim = (props) => {
const [ObtenerdataETH, setObtenerdataETH] = useState([]);
const [ObtenerdataBTC, setObtenerdataBTC] = useState([]);
const [ObtenerdataXRP, setObtenerdataXRP] = useState([]);
const DevuelveValorCrypto = testing => {
console.log("check received: ", testing)
const TipoCrypto = testing;
let test123 = ObtenerdataETH.price
console.log("check received: valor de test123", test123)
}
return <DIV> bla bla {DevuelveValorCrypto({})} </DIV>
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.