render方法中的Console.log显示state = true,但jsx显示false

问题描述 投票:0回答:2
  • 我有一个项目列表,我从componentDidMount中的API调用中返回。
  • 每个项目都有一个子列表,如果单击该项目(作为手风琴),我想要有条件地呈现该子列表。
  • 为了实现这一点,在componentDidMount中,我使用带有这个初始形式的ranges_status对象setState: key1: false, key2: false, ...
  • 然后在回调函数中,我将单击的项设置为true,之前单击为false(以手风琴方式呈现)。
  • 这一切在console.log上都很完美,但是JSX根本没有根据状态值进行更新,它只保留了我在componentDidMount中给出状态的初始值。

这是我的代码(总结只是为了说明问题):

class Hijos extends React.Component {

state = {
  ranges_status: {}
}

componentDidMount() {
    /* Here: API call and populate a ranges_status object with only 
    false values

    ranges_status: {
       'key1': false
       'key2': false
    }
    */

    /* set state */
    this.setState({ 
        ranges_status: ranges_status
    })
}


_handleOnPress = (clicked_key_range) => {

  /* Here I update the ranges_status object depending on which item was 
  clicked, so it can take a form like: 

  ranges_status: {
     'key1': true
     'key2': false
     'key3': false
  } */

  this.setState({ ranges_status: ranges_status })

}


render() {

const ranges_status = this.state.ranges_status

/* HERE I CONSOLE.LOG AND IT SHOWS IT EVERY TIME JUST HOW IT'S SUPPOSED 
TO BE, BUT THE JSX KEEPS SHOWING JUST THE INITIAL STATE VALUES (ALL 
FALSE) */

console.log("asdasdasd ", ranges_status)

return (
  <Container>
    <ViewsHeader title={'Hijos'} navigation={this.props.navigation} />
      <BasicHorseData/>
    <Content>
        <List
            dataArray={listHijosByRange}
            renderRow={(item) =>
              <ConditionalItem   key_range={item.key_range} is_active={this.state.ranges_status[item.key_range]} handle_on_press={this._handleOnPress} />
            }>
        </List>
    </Content>

     <ViewsFooter navigation={this.props.navigation} />

  </Container>
)
}
}


const ConditionalItem = (props) => {

   const is_active = props.is_active
   const key_range = props.key_range

   /* This shows false all the time */
   console.log(is_active)

   return(
     <ListItem
       button={true}
       onPress={() => props.handle_on_press(key_range)}
     >
       {/* THIS SHOWS FALSE ALL THE TIME TOO (here is where the 
       contional rendering is supposed to be) */}
       <Text>{is_active.toString()}</Text>
     </ListItem>
   )
}

提前致谢!

react-native jsx lifecycle
2个回答
0
投票

我希望List componet是NativeBase的形式,如果有的话,请检查以下链接:https://github.com/GeekyAnts/NativeBase/issues/698

这可能是一个问题“动态列表在数据刷新时不会刷新”正如NativeBase的开发人员所赞赏的那样,使用FlatListListItem

并确保添加

<FlatLsit
 extraData={this.state.ranges_status}  
 ...
/>

它将有助于更新数据


0
投票

我认为你需要在ConditionalItem组件中更改它。

const is_active = props.is_active

对此。

let is_active = props.is_active

const关键字阻止您覆盖is_active中的值。尝试将其更改为let关键字。希望它有效!

© www.soinside.com 2019 - 2024. All rights reserved.