【问题标题】:View not re-rendering after onPressonPress 后视图不重新渲染
【发布时间】:2019-10-17 04:29:54
【问题描述】:

我正在尝试在触发 onPress 事件时更改 React Native Card 组件的背景颜色。虽然我在 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()。

谢谢!

【问题讨论】:

  • 看看extraData 属性。添加extraData={categories} 能解决您的问题吗?
  • 哇,非常感谢!我为 extraData 属性分配了一个布尔值,然后在触发 onPress 时更改了它的状态。

标签: javascript react-native


【解决方案1】:

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

您可以通过在 extraData 属性中指定 FlatList 来让 state.itemsPressed 监听更改:

extraData={this.state.itemsPressed}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    相关资源
    最近更新 更多