为什么我得到 [object object ]

why i got [object object ]

import React, { Component } from "react";
import { Button, View ,Text ,StyleSheet, FlatList, ScrollView} from "react-native";
import DateTimePicker from "react-native-modal-datetime-picker";
import moment from 'moment'
import addDays from 'date-fns/addDays'
import Modal from 'react-native-modal';

export default class MExample extends Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      day:[],
      isDateTimePickerVisible: false,
      choseDate:'',
      visibleModal: false,
      lists:''
    };
  }


  showDateTimePicker = () => {
    this.setState({ isDateTimePickerVisible: true });
  };

  hideDateTimePicker = () => {
    this.setState({ isDateTimePickerVisible: false });
  };

  handleDatePicker = ( date ) => {
    // console.log("A date has been picked:", date); here date come correctly
    this.setState ({
      choseDate: 'Subscription start date ' + moment(date).format('MMMM, Do YYYY '),
    })
    this.hideDateTimePicker();
  };

  hideListPicker = () => {
    this.setState({ visibleModal: null ,list:[] });
  }; 

  handleListPicker = ( list ) => {
    console.log(list.toString()) 

    this.setState ({
      lists: 'list of start dates ' + list
    })
    this.hideListPicker();
  };

 
  getListViewItem = (item) => {
      let newList = this.state.list;
      if (newList.includes(item)) {
        let index = newList.indexOf(item);
        newList.splice(index,1);
        } else {
        newList.push(item);
      }
      this.setState({
        list: newList,
      });
 }

  renderModalContent = () => (
    <View>  
      <Text style={styles.textBox} onPress={this.showDateTimePicker}>Select Date</Text>    
        <DateTimePicker
          isVisible={this.state.isDateTimePickerVisible}
          onConfirm={this.handleDatePicker}
          onCancel={this.hideDateTimePicker}
          minimumDate = {new Date()}
          maximumDate = {addDays(new Date(), 30)}
            />
      
    <View style = {{backgroundColor:'white'}}>
            <View>
              <FlatList horizontal={true} 
                  data = {[{day: '1'},{day: '2'}, {day: '3'},{day: '4'}, {day: '5'},{day: '6'},{day: '7'}]}
                  renderItem={({item, index}) =>
                      <Text style={styles.textBox} key={index}
                            onPress={this.getListViewItem.bind(this, item.day)}>{item.day}
                      </Text>}
              />
              
                <ScrollView
                  style = {{marginHorizontal: 20}} 
                  horizontal={true}
                > 
                  {
                  this.state.list.map((l, index) => {
                      return(
                     index !== this.state.list.length - 1 ? <Text style={{fontSize:30, color:'red'}}>{l}, </Text> : <Text style={{fontSize:30, color:'red'}}>{l}</Text>
                      )
                    })
                  }
                </ScrollView>
                </View>
           </View>
      <Button
      onPress={this.handleListPicker}
        title="Submit"
      />
    </View>
  );

  render() {
     return (
        <>
       <Text style={{fontSize:20}}>Frequency</Text>
            <View style={styles.container} >
                <Text style={styles.textBox}  onPress={() => this.setState({ visibleModal: 'default' })}>Weekly </Text>
              </View>
              <Text style={{fontSize:20, color:'black', textAlign:'center'}}>{this.state.choseDate} </Text>
              <Text style={{fontSize:20, color:'black', textAlign:'center'}}>{this.state.lists} </Text>

           <Modal isVisible={this.state.visibleModal === 'default'} 
             onBackButtonPress={() => this.setState({ visibleModal: null, list:[] },  )}>
             {this.renderModalContent()}
           </Modal> 
         </>
    );
  }
}

const styles = StyleSheet.create({
  container:{
    flexDirection:'row', 
    flexWrap:'wrap',
    justifyContent:'center',
  },
  textBox :{
    fontSize:20,
    textAlign:'center',  
    borderWidth: 1,
    borderRadius: 12,
    borderColor: "#CBCBCB",
    margin:10,
    padding:5,
    backgroundColor:'#a0a3a3'
  },
});

我已经创建了模态 here user select date list and after submit i clear list in setState 为什么我在控制台中得到 [object object]

 export default class MExample extends Component {
   constructor(props) {
     super(props);
      this.state = {
         list: [],
         visibleModal: false,
         lists: ''
      };
    }

 hideListPicker = () => {
   this.setState({ visibleModal: null ,list:[] });
  }; 

 handleListPicker = ( list ) => {
  console.log(list.toString()) 
  // [object objcet]

  this.setState ({
     lists: 'list of start dates ' + list
   })
  this.hideListPicker();
 };

 render(){
   return( 
    // jsx <Text>{this.state.lists} </Text> // [object object]

   <Button onPress={this.handleListPicker}
    title="Submit"
  />
  )
}

因为方法 toString returns 它。对于打印对象数据,只需将对象传递给 console.log 方法,例如 console.log(list)

这是因为您将 event 作为 Button 单击时的参数传递,这是一个对象。现在当你使用 list.toString() 时,它会将这个 event 对象转换成字符串并显示给你 [Object Object]

您可以使用

来验证它
console.log("data = ",list) 

而不是

console.log(list.toString()) 

使用 JSON.stringify 代替 .toString 这个问题可能会帮助您 What's the difference in using toString() compared to JSON.stringify()? 理解其中的区别

let x = {a: 123, b: 321};
console.log("toString", x.toString());
console.log("stringified", JSON.stringify(x));

如果您有通告 JSON,您可能想访问 How can I print a circular structure in a JSON-like format? 以了解如何安慰这样的 JSONs

在您的情况下,只需删除 toString() 函数即可获得所需内容。

旁注:在浏览器环境中使用console.log时,当您的对象具有嵌套级别时,您可能会得到类似

的内容

> a: [...]

在 Web 控制台中单击 > 后,您会看到该值,但该值是在您单击时确定的,而不是 运行 通过您的 console.log 时确定的.

获取记录时值的最佳方法是使用 console.log(JSON.stringify(object))

要格式化 JSON 输出,将参数传递给 stringify 函数,如下所示:

console.log(
  JSON.stringify
    (
      obj, // the object you want to log
      null,
      2 // the indent counts by spaces for each level
    )
)