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

Console.log in render method shows state = true, but jsx shows false

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

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

提前致谢!

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

const is_active = props.is_active

到此。

let is_active = props.is_active

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

我希望List组件是NativeBase形式,如果是这样,请检查这个link:https://github.com/GeekyAnts/NativeBase/issues/698

这可能是 "Dynamic List won't refresh when data refreshes " 的问题 正如 NativeBase 的开发人员所推荐的那样,使用 FlatListListItem

并确保添加

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

有助于更新数据