【问题标题】:Property not being added to object属性未添加到对象
【发布时间】:2021-09-19 04:10:46
【问题描述】:

我有一个对象,里面有一个数组。每个数组有多个对象。所以使用 .map 函数,我在对象内的数组上循环。每个数组项都有一个单击功能,我可以在其中切换项。数组项的初始状态是this

{
    DisplayText: "Foresatte"
    Selectable: true
    UserRecipientToInclude: "IncludeGuardianRecipient"
}

当我这样做时

choice.Selected = 假

并且控制台记录新添加的项目在对象中不存在的结果。这是为什么呢?

这里是代码

{c.UserDropdownMenuChoices.map(choice => {
    return ( <TouchableHighlight
      {...testProperties(choice.DisplayText, true)}
      style={{ opacity: !choice.Selectable ? 0.4 : 1 }}
      onPress={() => {
        this.selectChoice(c.UserDropdownMenuChoices, choice, c)
      }}
      underlayColor={'transparent'}
      key={choice.DisplayText}
    >
      <View style={styles.choiceContainer}>
        {
          choice.selected ? (
            //<MaterialCommunityIcons name={'checkbox-marked'} style={styles.checkboxClick} size={20} />
            <Icon
              type={'material-community'}
              name={'checkbox-marked'}
              iconStyle={styles.checkboxClick}
              size={20}
            />
          ) : (
            <Icon
              type={'material-community'}
              name={'checkbox-blank-outline'}
              iconStyle={styles.checkboxDefault}
              size={20}
            />
          )
          //DONE: <MaterialCommunityIcons name={'checkbox-blank-outline'} style={styles.checkboxDefault} size={20} />
        }
        <Text style={styles.displayText}>{choice.DisplayText}</Text>
      </View>
    </TouchableHighlight> )}

而我的功能是这样的

  selectChoice(choicesList, choice, contact) {
    choice.selected = true
    ...
    console.log(choice) // doesn't have the new property
  }

此代码用于反应原生应用程序

【问题讨论】:

标签: javascript reactjs typescript react-native


【解决方案1】:

我之前解决了一个类似的问题,方法是简单地将 .map 中的选择钩子限定出来没有将属性映射到数组本身

所以我做的是:

import MenuRow from "./menu_row"
...

 const Rooms = allRooms.map((room, index) =>  {
   return (
      <MenuRow key={room.id} room={room}/>
   )
 })

在 MenuRow.js 中

const MenuRow = (props) => {
    let room = props.room
    const [selected, setSelected] = useState(true) // Checked by default
    return (
    
     <TouchableOpacity onPress={() => {setSelected(!selected), applySelected(room.id, selected) }}  style={s.checkrow}>
       ...
       {selected ? 
          // SELECTED
          <View style={s.checked}></View>
       :
          // NOT SELECTED
          <View style={s.unchecked}></View>
       }
     </TouchableOpacity>

)

不过,您也可以尝试一下: https://stackoverflow.com/a/44407980/4451733

【讨论】:

    猜你喜欢
    • 2015-06-13
    • 2022-11-19
    • 2014-08-26
    • 2015-11-15
    • 2015-09-21
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多