[英]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.