Javascript 如何在react native中调用函数内部的组件

Javascript 如何在react native中调用函数内部的组件,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我正在尝试使用react native创建应用程序。我在用世博会。 我有一个名为DistList的组件,它应该根据对象的条目数重复调用。但是,当在forEach中使用该组件时,不会调用该组件 HomeData.js import React from 'react'; import { StyleSheet, Text, View, SafeAreaView, Platform, StatusBar, ScrollView, Dimensions } from 'react-native';

我正在尝试使用react native创建应用程序。我在用世博会。 我有一个名为DistList的组件,它应该根据对象的条目数重复调用。但是,当在forEach中使用该组件时,不会调用该组件

HomeData.js

import React from 'react';
import { StyleSheet, Text, View, SafeAreaView, Platform, StatusBar, ScrollView, Dimensions } from 'react-native';

import dataCovid from '../store/dataCovid.json'
import DataList from './DataList.js'
import colors from './config/colors.js'


export default class HomeData extends React.Component{
  constructor(props) {
    super(props);


    this.state = {
      dataSource : '',
      currentTotal : 0,
      currentRecovered : 0,
      currentDecreased : 0,
      currentActive : 0,
    }
 }

fetchUsers(){
  fetch("https://api.covidindiatracker.com/state_data.json")
    .then(response => response.json())
    .then((responseJson)=> {
      this.setState({
       loading: false,
       dataSource: responseJson
      })

    })
    .catch(error=>console.log(error)) //to catch the errors if any
    // console.log(responseJson)
    // this.calculateCount();

}

  componentDidMount(){
    this.fetchUsers();
  }

  /* componentDidUpdate(){
    this.calculateCount();
  } */

    calculateCount(){
      console.log("cc")
      // console.log("cclen", this.state.dataSource)
      // console.log("cclen", this.state.dataSource.length)
      if(this.state.dataSource.length > 0){
        let data = /* JSON.stringify( */this.state.dataSource;
        // console.log(data)

        // if(recoveredResult == 0||decreasedResult == 0||activeResult == 0){
          console.log("inside")
        // var dataValue = Array.from(data)
        // var activeResult = data.map(activeVal => activeVal.active).reduce((nextValue, activeVal) => activeVal + nextValue);
        var recoveredResult = data.map(activeVal => activeVal.recovered).reduce((nextValue, activeVal) => activeVal + nextValue);
        var decreasedResult = data.map(activeVal => activeVal.deaths).reduce((nextValue, activeVal) => activeVal + nextValue);
        var activeResult = data.map(activeVal => activeVal.active).reduce((nextValue, activeVal) => activeVal + nextValue);
        var totalResult = recoveredResult+decreasedResult+activeResult;
        console.log(recoveredResult)
        console.log(decreasedResult)
        console.log(activeResult)

          this.setState({
            currentTotal : totalResult,
            currentRecovered : recoveredResult,
            currentDecreased : decreasedResult,
            currentActive : activeResult,
          })
        // }
        console.log(recoveredResult)
        console.log(this.state.currentRecovered)
        console.log(this.state.currentDecreased)
        console.log(this.state.currentActive)
      }
    }


    handleDataList=()=>{
      console.log("asdasd", this.state.dataSource.length)
      if(this.state.dataSource.length > 0){
        this.state.dataSource.forEach(function(element){
          console.log(element);
          return (
          <View>
          <DataList 
            state={element.state} 
            recovered={element.recovered} 
            decreased={element.deaths} 
            total= {element.confirmed+element.recovered+element.deaths+element.active}
            heading={true}
            />
            </View>
            );
      });
      }
    }


  render() {
    // console.log("erer", this.state.dataSource)
    // console.log("erer", this.state.currentRecovered)
    // console.log("erer", JSON.stringify(dataCovid) )
    if(this.state.currentActive == 0){
      this.calculateCount();
    }
    return (
        <View style={styles.container}>
      {/* <ScrollView> */}
          <View style={styles.containerTop}>
            <View style={styles.totalContainerOne}>
              <Text style={[styles.textStyle, styles.textTotal, ]}>Total</Text>
              <Text>[{this.state.currentTotal}]</Text>
            </View>
            <View style={styles.totalContainerTwo}>
              <View style={styles.recoveredContainer}>
                <Text style={[styles.textStyle, styles.textRecovered, ]}>Recovered</Text>
                <Text>[{this.state.currentRecovered}]</Text>
              </View>
              <View style={styles.decreasedContainer}>
                <Text style={[styles.textStyle, styles.textDecreased, ]}>Decreased</Text>
                <Text>[{this.state.currentDecreased}]</Text>
              </View>
              <View style={styles.activeContainer}>
                <Text style={[styles.textStyle, styles.textActive, ]}>Active</Text>
                <Text>[{this.state.currentActive}]</Text>
              </View>
            </View>
          </View>
          <View style={styles.containerBottom}>
            <DataList state="State" total="Total" recovered="Recovered" decreased="Decreased" heading={true}/>
            <DataList state="State" total="Total" recovered="Recovered" decreased="Decreased" heading={true}/>

              {
                this.handleDataList()

              }

          </View>
      {/* </ScrollView> */}
        </View>
    );
}
}

const styles = StyleSheet.create({
  container: {
    // width : '100%',
    // flex: 1,
    // height : '100%',
    // height: 1500,
    // flexDirection : 'row',
    // backgroundColor: 'blue',
    // alignItems: 'center',
    // justifyContent: 'space-evenly',
    // marginTop : Platform.OS === 'android' ? StatusBar.currentHeight : 0,
    // elevation : 5
  },

  containerTop: {
    // flex: 0.3,
    // height : '15%',
    height: Dimensions.get('window').height/3,
    // flexDirection : 'row',
    // backgroundColor: 'blue',
    alignItems: 'center',
    justifyContent: 'space-evenly',
    // marginTop : Platform.OS === 'android' ? StatusBar.currentHeight : 0,
    // elevation : 5
  },
  totalContainerOne: {
    height : '45%',
    // flex: 0.8,
    width : '90%',
    backgroundColor: '#eeeeee',
    elevation : 20,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius : 15,

  },
  textTotal:{
    color : colors.totalColor,
  },
  totalContainerTwo: {
    // flex: 0.8,
    width : '100%',
    height : '45%',
    // backgroundColor: 'green',
    flexDirection : 'row',
    justifyContent : 'space-evenly'
  },
  recoveredContainer: {
    // flex: 1,
    width : '30%',
    // height : '45%',
    backgroundColor: '#eeeeee',
    elevation : 50,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius : 15,
  },
  textRecovered:{
    color : colors.recoveredColor,
  },
  decreasedContainer: {
    // flex: 1,
    width : '30%',
    // height : '45%',
    backgroundColor: '#eeeeee',
    elevation : 50,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius : 15,
  },
  textDecreased:{
    color : colors.decreasedColor,
  },
  activeContainer: {
    // flex: 1,
    width : '30%',
    // height : '45%',
    backgroundColor: '#eeeeee',
    elevation : 50,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius : 15,
  },
  textActive:{
    color : colors.activeColor,
  },
  textStyle:{
    fontSize : 18,
    fontWeight : '700',
  },

  containerBottom: {
    paddingTop : 10,
    // flex: 0.4,
    // height:'85%',
    // flexDirection : 'row',
    // backgroundColor: 'blue',
    alignItems: 'center',
    justifyContent: 'space-evenly',
    // marginTop : Platform.OS === 'android' ? StatusBar.currentHeight : 0,
    // elevation : 5
  },
});

import React from 'react';
import { StyleSheet, Text, View, SafeAreaView, Platform, StatusBar, ScrollView, Dimensions } from 'react-native';

import dataCovid from '../store/dataCovid.json'
import colors from './config/colors.js'


export default class DataList extends React.Component{
  constructor(props) {
    super(props);

    this.state = {
    }
 }
  render() {
      const {state, total, recovered, decreased, heading} = this.props;
      const testStyle = (heading)? styles.testHeadingStyle : styles.dataStyle
    return (
        <View style={styles.container}>
            <View style={styles.stateBox}>
                <Text style={testStyle}>{state}</Text>
            </View>
            <View style={styles.stateBox}>
                <Text style={testStyle}>{total}</Text>
            </View>
            <View style={styles.stateBox}>
                <Text style={testStyle}>{recovered}</Text>
            </View>
            <View style={styles.stateBox}>
                <Text style={testStyle}>{decreased}</Text>
            </View>
        </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    width : '100%',
    flex: 1,
    // height : '100%',
    // height: 1500,
    flexDirection : 'row',
    // backgroundColor: 'blue',
    alignItems: 'center',
    justifyContent: 'space-evenly',
    // marginTop : Platform.OS === 'android' ? StatusBar.currentHeight : 0,
    // elevation : 5
  },
  stateBox:{
    height : 30,
    width : 87,
    backgroundColor : '#f6f6f7',
    borderRadius : 5,
    // top : 5,
    justifyContent : 'center',
    // alignItems : 'center',
    elevation : 5,
    textAlign : 'left',
    paddingLeft : 5,


  },
  testHeadingStyle:{
    fontSize : 15,
    fontWeight : '700',
    color : '#6c757d',
    textShadowColor: 'rgba(0, 0, 0, 0.50)',
    textShadowOffset: {width: -1, height: 1},
    textShadowRadius: 10,
  },
  dataStyle:{
    fontSize : 15,
    fontWeight : '700',
    color : '#6c757d',
    // textShadowColor: 'rgba(0, 0, 0, 0.50)',
    // textShadowOffset: {width: -1, height: 1},
    // textShadowRadius: 10,
  }
});
从“React”导入React;
从“react native”导入{样式表、文本、视图、安全区域视图、平台、状态栏、滚动视图、维度};
从“../store/dataCovid.json”导入dataCovid
从“./DataList.js”导入数据列表
从“./config/colors.js”导入颜色
导出默认类HomeData扩展React.Component{
建造师(道具){
超级(道具);
此.state={
数据源:“”,
现时总数:0,,
当前已恢复:0,
当前值:0,
当前活动:0,
}
}
fetchUsers(){
取回(“https://api.covidindiatracker.com/state_data.json")
.then(response=>response.json())
.然后((responseJson)=>{
这是我的国家({
加载:false,
数据来源:responseJson
})
})
.catch(error=>console.log(error))//以捕获错误(如果有)
//console.log(responseJson)
//这是calculateCount();
}
componentDidMount(){
this.fetchUsers();
}
/*componentDidUpdate(){
这是calculateCount();
} */
calculateCount(){
控制台日志(“cc”)
//log(“cclen”,this.state.dataSource)
//log(“cclen”,this.state.dataSource.length)
如果(this.state.dataSource.length>0){
让data=/*JSON.stringify(*/this.state.dataSource;
//console.log(数据)
//如果(recoveredResult==0 | | decreasedResult==0 | | activeResult==0){
控制台日志(“内部”)
//var dataValue=Array.from(数据)
//var-activeResult=data.map(activeVal=>activeVal.active).reduce((nextValue,activeVal)=>activeVal+nextValue);
var recoveredResult=data.map(activeVal=>activeVal.recovered).reduce((nextValue,activeVal)=>activeVal+nextValue);
var decreasedResult=data.map(activeVal=>activeVal.Death).reduce((nextValue,activeVal)=>activeVal+nextValue);
var-activeResult=data.map(activeVal=>activeVal.active).reduce((nextValue,activeVal)=>activeVal+nextValue);
var totalResult=recoveredResult+decreasedResult+activeResult;
console.log(recoveredResult)
console.log(decreasedResult)
日志(activeResult)
这是我的国家({
currentTotal:totalResult,
currentRecovered:recoveredResult,
电流减小:结果减小,
currentActive:activeResult,
})
// }
console.log(recoveredResult)
console.log(this.state.currentRecovered)
console.log(this.state.currentDecreated)
console.log(this.state.currentActive)
}
}
handleDataList=()=>{
log(“asdasd”,this.state.dataSource.length)
如果(this.state.dataSource.length>0){
this.state.dataSource.forEach(函数(元素){
控制台日志(元素);
返回(
);
});
}
}
render(){
//log(“erer”,this.state.dataSource)
//console.log(“erer”,this.state.currentRecovered)
//log(“erer”,JSON.stringify(dataCovid))
如果(this.state.currentActive==0){
这是calculateCount();
}
返回(
{/*  */}
全部的
[{this.state.currentTotal}]
恢复
[{this.state.currentRecovered}]
降低
[{this.state.currentDescented}]
活跃的
[{this.state.currentActive}]
{
这个。handleDataList()
}
{/*  */}
);
}
}
const styles=StyleSheet.create({
容器:{
//宽度:“100%”,
//弹性:1,
//高度:“100%”,
//身高:1500,
//flexDirection:'行',
//背景颜色:“蓝色”,
//对齐项目:“居中”,
//为内容辩护:“间隔均匀”,
//marginTop:Platform.OS=='android'?StatusBar.currentHeight:0,
//立面图:5
},
集装箱码头:{
//弹性系数:0.3,
//身高:15%,
高度:尺寸。获取(“窗口”)。高度/3,
//flexDirection:'行',
//背景颜色:“蓝色”,
对齐项目:“居中”,
为内容辩护:“间隔均匀”,
//marginTop:Platform.OS=='android'?StatusBar.currentHeight:0,
//立面图:5
},
全速导航:{
身高:45%,
//弹性系数:0.8,
宽度:“90%”,
背景颜色:“#eeeeee”,
海拔:20,
对齐项目:“居中”,
为内容辩护:“中心”,
边界半径:15,
},
text总计:{
颜色:colors.totalColor,
},
totalContainerTwo:{
//弹性系数:0.8,
宽度:“100%”,
身高:45%,
//背景颜色:“绿色”,
flexDirection:'行',
为内容辩护:“空间均匀”
},
回收容器:{
//弹性:1,
宽度:“30%”,
//身高:45%,
背景颜色:“#eeeeee”,
标高:50,
对齐项目:“居中”,
为内容辩护:“中心”,
边界半径:15,
},
文本恢复:{
颜色:colors.recoveredColor,
},
递减容器:{
//弹性:1,
宽度:“30%”,
//身高:45%,
背景颜色:“#eeeeee”,
标高:50,
对齐项目:“居中”,
为内容辩护:“中心”,
边界半径:15,
},
文本减少:{
颜色:colors.decreatedColor,
},
activeContainer:{
//弹性:1,
宽度:“30%”,
//身高:45%,
背景颜色:“#eeeeee”,
标高:50,
对齐项目:“居中”,
为内容辩护:“中心”,
边界半径:15