在onPress之后查看不重新渲染

时间:2019-05-31 13:58:03

标签: javascript react-native

我正在尝试在触发onPress事件时更改React Native Card组件的backgroundColor。尽管我在componentDidUpdate上看到状态的变化,但是我没有看到它。

触发onPress事件时,我正在更改itemsPressed数组的值。如果按下的项目ID已在数组中,则将其删除,否则将其添加到数组中。

export default class Popular extends Component {

 constructor(props) {
    super(props);
    this.togglePressed = this.togglePressed.bind(this);

    this.state = {
     categories: [],
     itemsPressed: []
   }
 }

 togglePressed = item => {
    const id = item.id;
    this.setState(({ itemsPressed }) => ({
      itemsPressed: this.isItemPressed(item)                       
      ? itemsPressed.filter(a => a != id)                            
      : [...itemsPressed, id],
    }))
 };

 isItemPressed = item => {
  const id = item.id;
  return this.state.itemsPressed.includes(id);
 };

 componentDidMount() {
   this.setState({
     categories:this.props.categories,
   });
 }

 componentDidUpdate(){
  console.log(this.state.itemsPressed);
 }

 renderTabItem = ({ item,index }) => (
  <TouchableOpacity
   style={styles.category}
   key={index}
   onPress={() => this.togglePressed(item)}
  >
   <Card center 
    style={[styles.card,{backgroundColor: 
          this.isItemPressed(item) 
          ? item.color 
          : 'gray' 
     }]}>
     <Image source={item.icon} style={styles.categoryIcon}/>
   </Card>
   <Text size={12} center style={styles.categoryName} 
     medium color='black'
    >
    {item.name.toLowerCase()}
   </Text>
 </TouchableOpacity>
 );

renderTab(){
  const {categories} = this.state;
  return (
    <FlatList
    horizontal = {true}
    pagingEnabled = {true}
    scrollEnabled = {true}
    showsHorizontalScrollIndicator={false}
    scrollEventThrottle={16}
    snapToAlignment='center'
    data={categories}
    keyExtractor={(item) => `${item.id}`}
    renderItem={this.renderTabItem}
   />
 )
}
  render() {
    return (
       <ScrollView>
        {this.renderTab()}
       </ScrollView>
   );
  }
 }

我希望外观有所变化,但无法重新渲染renderTab()。

谢谢!

1 个答案:

答案 0 :(得分:1)

您的FlatList具有属性category作为数据源,因此只有在检测到category属性发生变化时,它才会重新呈现单元格。但是,您的代码仅更改itemsPressed,因此不会重新渲染任何单元格。

您可以通过在extraData属性中指定FlatList来通知state.itemsPressed

extraData={this.state.itemsPressed}
相关问题