Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何访问渲染函数中的状态对象错误_Reactjs_React Native_Redux_React Redux - Fatal编程技术网

Reactjs 如何访问渲染函数中的状态对象错误

Reactjs 如何访问渲染函数中的状态对象错误,reactjs,react-native,redux,react-redux,Reactjs,React Native,Redux,React Redux,我正在创建一个react本机应用程序,在访问render中的状态时遇到问题 我可以将状态(this.state)记录到console.log中,它将显示log所期望的内容 如果我使用console.log之类的东西。。。(this.state.value)即使该值存在,也会出错 我想不出来,我已经试了一整天了 import React, { Component } from 'react'; import { AsyncStorage, ScrollView, Text, View } from

我正在创建一个react本机应用程序,在访问render中的状态时遇到问题

我可以将状态(this.state)记录到console.log中,它将显示log所期望的内容

如果我使用console.log之类的东西。。。(this.state.value)即使该值存在,也会出错

我想不出来,我已经试了一整天了

import React, { Component } from 'react';
import { AsyncStorage, ScrollView, Text, View } from 'react-native';
import { connect } from 'react-redux';
import Loader from '../common/loaders/Loader';
import Header from '../common/header/Header';
import moment from 'moment';
import number from '../../utils/numbers';
import dateLabel from '../../utils/dateLabel';

// Content
import i18n from '../../i18n/i18n';

// Actions
import { loginUser, logoutUser } from '../../actions/authActions';
import { loadingBegin, loadingFinish } from '../../actions/loadingActions';
import { accountsList } from '../../actions/accountsActions';

// Services
import { getAccounts } from '../../services/account';
import { getTransactions } from '../../services/transaction';

// Styles
import common from '../../styles/common';
import styles from './styles';

// --- --- ---
class Home extends Component {

state = {};

constructor(props) {
    super(props);

    if (!this.props.auth.authenticated) this.props.navigation.navigate('Unauthorised');

    this.props.loadingBegin();

    this.state = {
    accounts: [],
    balances: null,
    categories: null,
    transactions: null,
    meta: null,
    };

    this._bootstrapAsync();

    this.props.loadingFinish();
}

componentDidMount = () => {
    const {navigation} = this.props;
    navigation.addListener ('willFocus', () =>{
    console.log('RE-RUNNING PAGE');
    });
}

_bootstrapAsync = async () => {
    // Grab the filter values
    // TODO -> Put filters into Redux store
    this.filters = JSON.parse(await AsyncStorage.getItem('filters'));

    // Check to see if we have any accounts already added
    // Get the accounts info and prime the redux store and state
    const accounts = await getAccounts(this.props.auth);
    this.props.accountsList(accounts);
    this.setState({
    accounts,
    });

    // If there aren't any accounts, redirect to add an account
    if (this.state.accounts && this.state.accounts.length === 0) this.props.navigation.navigate('AccountsNone');

    // Grab the latest transactions and set the state (to be used later)
    let transactionsOptions = {};
    if (this.filters && this.filters.filtersForm) {
    // date set period
    if (this.filters.filtersForm.dates) transactionsOptions.date_type = this.filters.filtersForm.dates;
    // dates between
    if (this.filters.filtersForm.fromDate && this.filters.filtersForm.toDate) {
        transactionsOptions.date_from = this.filters.filtersForm.fromDate;
        transactionsOptions.date_to = this.filters.filtersForm.toDate;
    }
    }
    if (this.filters && this.filters.accountSwitches && this.filters.accountSwitches.length > 0) {
    let obj = this.filters.accountSwitches;
    Object.keys(obj).forEach(key => {
        if (data.accountSwitches[key]) {
        if (!transactionsOptions.account_ids) transactionsOptions.account_ids = {};
        transactionsOptions.account_ids += ',' + key;
        }
    });
    };

    console.log(transactionsOptions);

    let transactions = await getTransactions(this.props.auth, transactionsOptions);
    let meta = transactions.meta;
    let data = transactions.data;

    const balances = this.state.transactions.Balances.map((value) => {                
        return {
            label: moment(value.date, "YYYY-MM-DD").format("MMM Do"), 
            value: value.amount
        }
    });

    const categories = this.state.transactions.Categories;

    this.setState({ 
    transactions: data,
    meta,
    balances,
    categories,
    });
};

render() {
    const { ...props } = this.props;
    const loading = this.props.loading.inProgress;
    let body;

    if (loading) {
    body = <Loader visible={loading} />;
    } else {
    body = (<View>
        <Text style={[styles.balancesDate]}>nuffink</Text>  
    </View>);
    }

    console.log('state.TRANSACTIONS');
    console.log(this.state); // <----------------this works
    console.log(this.state.transactions); // <----------------this doesn't work
    console.log('state.TRANSACTIONS //');

    return (
    <ScrollView
        style={[common.body, styles.container]}
        ref='_main'
        contentContainerStyle={{
        flexGrow: 1
        }}
        stickyHeaderIndices={[0]}
    >

        <Header {...props} txt={"DASHBOARD"} />

        <View style={[common.containerPadding, styles.balances]}>
        <Text>{this.state.trasnactions.value}</Text> <--------------- kills the app and my soul
        </View>
    </ScrollView>
    )
}

}

const mapStateToProps = (state) => {
const { accounts, auth, loading } = state;
return { 
    accounts,
    auth,
    loading
};
};

export default connect(mapStateToProps, { accountsList, loadingBegin, loadingFinish, loginUser, logoutUser })(Home);
import React,{Component}来自'React';
从“react native”导入{AsyncStorage,ScrollView,Text,View};
从'react redux'导入{connect};
从“../common/loaders/Loader”导入加载程序;
从“../common/Header/Header”导入标题;
从“力矩”中导入力矩;
从“../../utils/numbers”导入编号;
从“../../utils/dateLabel”导入日期标签;
//内容
从“..//i18n/i18n”导入i18n;
//行动
从“../../actions/authActions”导入{loginUser,logoutUser};
从“../../actions/loadingActions”导入{loadingBegin,loadingFinish};
从“../../actions/accountsActions”导入{accountsList};
//服务
从“../../services/account”导入{getAccounts};
从“../../services/transaction”导入{getTransactions};
//风格
从“../../styles/common”导入公共项;
从“./styles”导入样式;
// --- --- ---
类Home扩展组件{
状态={};
建造师(道具){
超级(道具);
如果(!this.props.auth.authenticated)this.props.navigation.navigate('unauthorized');
this.props.loadingBegin();
此.state={
账户:[],
余额:空,
类别:空,
交易记录:空,
梅塔:空,
};
这个。_bootstrapAsync();
this.props.loadingFinish();
}
componentDidMount=()=>{
const{navigation}=this.props;
navigation.addListener('willFocus',()=>{
log(“重新运行页面”);
});
}
_bootstrapAsync=async()=>{
//获取过滤器值
//TODO->将过滤器放入Redux存储
this.filters=JSON.parse(等待AsyncStorage.getItem('filters');
//查看我们是否已添加任何帐户
//获取帐户信息并初始化redux存储和状态
const accounts=wait getAccounts(this.props.auth);
此.props.accountsList(accounts);
这是我的国家({
账户
});
//如果没有任何帐户,请重定向以添加帐户
如果(this.state.accounts&&this.state.accounts.length==0)this.props.navigation.navigate('AccountsNone');
//获取最新的事务并设置状态(稍后使用)
让TransactionOptions={};
if(this.filters&&this.filters.filtersForm){
//日期设定期间
if(this.filters.filtersForm.dates)TransactionOptions.date_type=this.filters.filtersForm.dates;
//日期介于
if(this.filters.filtersForm.fromDate&&this.filters.filtersForm.toDate){
TransactionOptions.date_from=this.filters.filtersForm.fromDate;
TransactionOptions.date_to=this.filters.filtersForm.toDate;
}
}
if(this.filters&&this.filters.accountSwitches&&this.filters.accountSwitches.length>0){
设obj=this.filters.accountSwitches;
Object.keys(obj.forEach)(key=>{
if(data.accountSwitches[键]){
如果(!TransactionOptions.account_ID)TransactionOptions.account_ID={};
TransactionOptions.account_id+=','+键;
}
});
};
console.log(TransactionOptions);
let transactions=Wait getTransactions(this.props.auth,TransactionOptions);
让meta=transactions.meta;
让data=transactions.data;
const balances=this.state.transactions.balances.map((值)=>{
返回{
标签:力矩(value.date,“YYYY-MM-DD”)。格式(“MMM-Do”),
value:value.amount
}
});
const categories=this.state.transactions.categories;
这个.setState({
交易:数据,
元,
余额,
类别,
});
};
render(){
const{…props}=this.props;
常量加载=this.props.loading.inProgress;
让身体;
如果(装载){
body=;
}否则{
正文=(
努芬克
);
}
console.log('state.TRANSACTIONS');

console.log(this.state);//
{this.state.trasnactions.value}这是因为
this.state.transactions
一开始是空的(在构造函数中设置),您无法访问未定义的属性。另外,您在渲染函数中的
中拼写了“transactions”

解决此问题的一种方法是,在尝试访问
this.state.transactions.value
之前,在渲染中检查是否定义了
this.state.transactions
,例如


{this.state.transactions&&{this.state.transactions.value}

谢谢。我在更改网站示例时犯了拼写错误-抱歉!我尝试了检查,但不幸的是,它不起作用。我需要的值是…this.state.transactions.somethingese.somethingese…。另外,_bootstrapAsync函数是否覆盖了状态中的空值或者我应该用另一种方式初始化?谢谢。你说的“不工作”是什么意思?没有呈现?如果有错误,具体是什么。是的,
\u bootstrapAsync
会覆盖它,但顾名思义是异步的,这意味着组件在运行时会继续装载和呈现。因此,它会在该函数完成执行之前呈现,因此它最初会以空事务呈现。很抱歉,t他给出了模糊的注释。即使我添加了值检查,它也不会输出值。例如…{this.state.transactions?${this.state.transactions.meta.Criteria.DateType}:null}它没有显示错误,但也没有显示state中的值。关于异步函数,这一点很好。谢谢!@user3303836,如果在render中打印
this.state.transactions
,填充后,对象中是否有
.meta.Criteria.DateType
属性?
<Text>{this.state.trasnactions.value}</Text> <--------------- kills the app and my soul
{this.state.transactions ? 
   <Text>{this.state.transactions.value}</Text>
: null }