未将属性添加到对象

时间:2021-07-08 17:04:20

标签: javascript reactjs typescript react-native

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

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

当我这样做

choice.Selected = false

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

这是代码

{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
  }

此代码用于 React Native 应用程序

1 个答案:

答案 0 :(得分:-1)

我之前通过简单地确定 .map 中的 select 钩子范围解决了类似的问题而不将属性映射到数组本身

所以我所做的是:

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

相关问题