如何将值从一个对象赋值给另一个对象

How to assign values from one object to another

我正在尝试做一些简单的事情,我有一个包含数据的对象。我正在尝试从该对象中获取值并将其分配给我将在下游使用的另一个对象。

我试过几种设置值的方法

 async componentDidMount () {
 try {
   const array = [

    {
      expanded: false, category_Name: "Mobiles", sub_Category: [{ 
 id: 1, name: 'Mi' }, { id: 2, name: 'RealMe' }, { id: 3, name: 
 'Samsung' }, { id: 4, name: 'Infinix' }]
  },
  {
    expanded: false, category_Name: "Laptops", sub_Category: [{ id: 
    8, name: 'Dell' }, { id: 9, name: 'MAC' }, { id: 10, name: 'HP' 
   }, { id: 11, name: 'ASUS' }]
  }
  ];

  const graphqldata =  await 
  API.graphql(graphqlOperation(listTodos))

  console.log('graphqldata:', graphqldata)

  this.setState({ AccordionData: array}, () => {});
  this.setState({ todos: graphqldata.data.listTodos.items })
  const items = this.state.todos.map((item, key) =>
  console.log("printing just name", item.name)
  var singleAccordion = new Object()
  singleAccordion.category_Name=item.name
  singleAccordion.expanded=falise
  singleAccordion.sub_Category=[{1,item.date},{2,item.location}, 
  {3,item.organizer}]
  console.log("AND PRINTING singleAccordion", singleAccordion)
  )
  console.log('AccordionData:', this.state.AccordionData)
  } catch (err) {
  console.log('error fetching data: ', err)
  }
  }`

我希望 "item" 对象中的值能够按照我尝试转换一个对象的方式分配到 singleAccordian 对象中。但我收到一个错误: 189 | const items = this.state.todos.map((item, key) => 190 | console.log("printing just name", item.name)

191 | var singleAccordion = new Object() | ^ 192 | singleAccordion.category_Name=item.name 193 | 194 | console.log("AND PRINTING singleAccordion", singleAccordion)

你的代码没有解释主要问题,我看到那段代码有一些错误,我不能写出准确的答案,但我可以帮助你减少错误:

缩进很重要:

async componentDidMount() {
  try {
    const array = [
      {
        expanded: false,
        category_Name: "Mobiles",
        sub_Category: [
          { id: 1, name: 'Mi' },
          { id: 2, name: 'RealMe' },
          { id: 3, name: 'Samsung' },
          { id: 4, name: 'Infinix' },
        ],
      },
      {
        expanded: false,
        category_Name: "Laptops",
        sub_Category: [
          { id: 8, name: 'Dell' },
          { id: 9, name: 'MAC' },
          { id: 10, name: 'HP' },
          { id: 11, name: 'ASUS' },
        ],
      }
    ];
    // What listTodos mean?
    const graphqldata = await API.graphql(graphqlOperation(listTodos));

    console.log('graphqldata:', graphqldata)
    //  Unnecesary
    // this.setState({ AccordionData: array });

    // You need to pass a function to run after the state changes
    this.setState({
      AccordionData: array,
      todos: graphqldata.data.listTodos.items,
    }, () => {
      this.state.todos.map((item) => { // You forgot to wrap your map function
        console.log("printing just name", item.name)
        const singleAccordion = {}; // Better than new Object()
        singleAccordion.category_Name = item.name;
        singleAccordion.expanded = false;
        singleAccordion.sub_Category = [
          { id: 1, name: item.date },
          { id: 2, name: item.location },
          { id: 3, name: item.organizer },
        ];
        console.log("AND PRINTING singleAccordion", singleAccordion)
      });
    })
    // This isn't available till state has changed
    console.log('AccordionData:', this.state.AccordionData)
  } catch (err) {
    console.log('error fetching data: ', err)
  }
}

希望对您有所帮助。

按问题 OP 编辑​​:这是其余代码和渲染方法:

 class AboutScreen extends React.Component {
 render(){
  return(
    <View style={styles.Panel_Holder}>
    <Text style={styles.category_Text}>About Screen </Text>
    <Text style={styles.sub_Category_Textt}>Put a mission statement 
    </Text>
   <Button
      title="Go to Home"
      onPress={() => this.props.navigation.navigate('Home')}
   />
   </View>

  )
 }
 }

  class Expandable_ListView extends Component {

  constructor() {

  super();

  this.state = {

  layout_Height: 0

  }
  }

 componentWillReceiveProps(nextProps) {
  if (nextProps.item.expanded) {
     this.setState(() => {
     return {
      layout_Height: null
     }
   });
  }
  else {
    this.setState(() => {
      return {
        layout_Height: 0
      }
      });
   }
   }

   shouldComponentUpdate(nextProps, nextState) {
   if (this.state.layout_Height !== nextState.layout_Height) {
     return true;
   }
   return false;
  }

  show_Selected_Category = (item) => {
  Alert.alert(item);

  }

 render() {
 return (
  <View style={styles.Panel_Holder}>

    <TouchableOpacity activeOpacity={0.8} onPress= . 
    {this.props.onClickFunction} style={styles.category_View}>

      <Text style={styles.category_Text}> . 
     {this.props.item.category_Name} </Text>

      <Image
        source={{ uri: 'https://reactnativecode.com/wp- 
        content/uploads/2019/02/arrow_right_icon.png' }}
        style={styles.iconStyle} />

    </TouchableOpacity>

    <View style={{ height: this.state.layout_Height, overflow: 
    'hidden' }}>

      {
        this.props.item.sub_Category.map((item, key) => (

          <TouchableOpacity key={key} style= . 
       {styles.sub_Category_Text} onPress= . 
       {this.show_Selected_Category.bind(this, item.name)}>

            <Text> {item.name} </Text>

            <View style={{ width: '100%', height: 1, backgroundColor: 
          '#000' }} />

          </TouchableOpacity>

        ))
       }

      </View>

    </View>

   );
  }
  }

  class HomeScreen extends React.PureComponent {

   state = { isloading: true, name: '', date: '', location: '', 
   organizer: '', sections:'', link:'', description:'', todos: [], 
   AccordionData: [], AccordianPlus:[] }


   async componentDidMount () {
   try {
     const array = [

    {
      expanded: false, category_Name: "Mobiles", sub_Category: [{ id: 
     1, name: 'Mi' }, { id: 2, name: 'RealMe' }, { id: 3, name: 
    'Samsung' },
    { id: 4, name: 'Infinix' }, { id: 5, name: 'Oppo' }, { id: 6, 
    name: 'Apple' }, { id: 7, name: 'Honor' }]
    }
    ];

   const graphqldata =  await 
       API.graphql(graphqlOperation(listTodos))

   console.log('graphqldata:', graphqldata)

   this.setState({
    isloading: false,
    AccordionData: [],
    AccordianPlus: [],
    todos: graphqldata.data.listTodos.items,
    }, () => {
     this.state.todos.map((item) => { // You forgot to wrap your map 
    function
    console.log("printing just name", item.name)
    const singleAccordion = {}; // Better than new Object()
    singleAccordion.category_Name = item.name;
    singleAccordion.expanded = false;
    singleAccordion.sub_Category = [
      { id: 1, name: item.date },
      { id: 2, name: item.location },
      { id: 3, name: item.organizer },
    ];
    console.log("AND PRINTING singleAccordion", singleAccordion)
    this.state.AccordianPlus.push(singleAccordion)

  });
})
 console.log('AccordionData:', this.state.AccordionData)
 console.log("Did AccordionPlus work?", this.state.AccordianPlus)
 this.state.AccordionData.push(this.state.AccordianPlus)
 console.log("Did final concat work?", this.state.AccordionData)
 } catch (err) {
  console.log('error fetching data: ', err)
 }
 }

 update_Layout = (index) => {

LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);

const array = [...this.state.AccordionData];

array[index]['expanded'] = !array[index]['expanded'];

this.setState(() => {
return {
  AccordionData: array
}
});
}

render() {

if (this.state.isloading){
   return <View><Text>Loading...</Text></View>;
 }
return (
  <View style={styles.MainContainer}>
  <Button
    title="About"
    onPress={() => this.props.navigation.navigate('About')}
  />
  <Text style={styles.Title_Text} > Hello Chess Finder </Text>
  <ScrollView contentContainerStyle={{ paddingHorizontal: 10, 
   paddingVertical: 5 }}>
    {
      this.state.AccordionData.map((item, key) =>
        (
          <Expandable_ListView key={item.category_Name} 
        onClickFunction={this.update_Layout.bind(this, key)} item= . 
     {item} />
        ))
    }
  </ScrollView>

  </View>
  );
 }
 }