reactjs - 将需要参数的函数正确传递给 PureComponent

标签 reactjs react-native

我正在使用 FlatList,在我的 renderItem 中我有一个名为 GridItem 的 PureComponent。我正在尝试传递需要 item 参数的函数 wishlistAddPresed,但是当以这种方式完成时,即使“item”没有改变,PureComponent 项目也会在每次状态更改时重新呈现。

我该如何解决这个问题?谢谢!

  wishlistAddPresed = (item) => console.log(item)

  renderItem = ({item}) => {
    return (
        <GridItem
            item={item}
            wishlistAddPresed={this.wishlistAddPresed(item)}
        />
    )
  }

  render () {
      console.log("Render products grid");
      return(
          <View style={styles.container}>
              <FlatList
                  data={this.state.data}
                  renderItem={this.renderItem}
                  keyExtractor={(item, index) => item.id}
              />
          </View>
      );
  }

在我的 GridItem 渲染中我有:

<TouchableOpacity style={styles.colButtonsG} onPress={this.props.wishlistAddPresed}>
    <IconG name='playlist-add-check' size={26} color="green" style={styles.icon} />
</TouchableOpacity>

最佳答案

诀窍是同时传递回调函数和参数(您已经在做),然后嵌套组件中,将项目传递给匿名回调。因此,在您的情况下,您需要执行以下操作:

<FlatList
  data={this.state.data}
  renderItem={({ item }) => {
    return <GridItem item={item} wishlistAddPressed={this.wishlistAddPressed} />
  }}
  keyExtractor={(item, index) => item.id}
/>

对于扩展 PureComponent 的 GridItem...

class GridItem extends React.PureComponent {
  render() {
    const {item, wishlistAddPresed} = this.props;

    return (
      <TouchableOpacity onPress={() => wishlistAddPressed(item)}>
        <IconG name="playlist-add-check" size={26} color="green" style={styles.icon} />
      </TouchableOpacity>
    );
  }
}

以这种方式完成后,wishlistAddPressed 会针对该行的特定项目进行调用,并保持函数相等性,这样 PureComponent 就不会像它应该的那样不正确地重新呈现。

关于reactjs - 将需要参数的函数正确传递给 PureComponent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45798706/

相关文章:

android - 在 Android 设备上启动时出现问题。 react-native-navigation 错误

android - 将 Firestore 与移动 native 应用程序(React native )一起使用时的逆向工程风险

javascript - 如何修复您应该只在 IOS 的应用程序中显式渲染一个导航器

javascript - 从多个源异步更新 React 状态

reactjs - 如何在 Storybook 中主题化 Material UI

javascript - 如何在 React.js 中使按钮具有交互性?

javascript - 如何编写 Javascript API 包装器

react-native - map 内的 Saga 调用不起作用

javascript - 异步函数不在 android 上返回

react-native 检查并提示用户启用网络/GPS