道具不会传播给孩子

时间:2018-02-06 18:53:52

标签: react-native state react-props

我正在努力添加滑动以删除我们正在开发的应用的功能。由于我们没有使用外部库来处理这个问题,所以我自己写的。

在我的项目中,我有一个容器,我保持状态。我使用setState更新状态,并将状态传递给此子组件作为prop。在下面的组件中,componentWillReceiveProps在发生时调用正确的值更新,但其子组件未接收其props的更新。如果这没有足够的意义,或者您需要查看更多代码,请告诉我。我只包含了我觉得相关的代码部分,因为这是一个私人项目。

  constructor(props) {
    super(props);

    this.renderWishlistRow = this.renderWishlistRow.bind(this);
  }

  renderWishlistRow(product) {
    return (
      <WishlistRow
        item={product}
        onItemPress={this.props.onItemPress}
        onRemoveAction={this.props.onRemoveAction}
        shouldCloseRemoveButton={this.props.shouldCloseRemoveButton}
        onScrollAction={this.props.onScrollAction}
        itemPressed={this.props.itemPressed}
        onEndScroll={this.props.onEndScroll}
      />
    );
  }

然后,在渲染函数中:

return (
  <KeyboardAwareListView
    dataSource={this.props.dataSource}
    renderRow={this.renderWishlistRow}
    renderSeparator={renderCardDividerAsSeparator}
    onScrollBeginDrag={this.props.onScrollAction}
    scrollEventThrottle={16}
    onScrollEndDrag={this.props.onEndScroll}
  />
);

提前感谢您的帮助。

编辑: 我使用以下代码在父组件中设置状态:

this.setState({
  shouldCloseRemoveButton: true,
});

我最初没有包含它,因为正在使用父组件的正确状态更改调用componentWillReceiveProps

编辑2: 应用程序这一部分的我的应用程序层次结构如下:

WishlistContainer: contains the setState calls and passes as a prop: shouldCloseRemoveButton={this.state.shouldCloseRemoveButton}
    Wishlist: passes props to its child WishlistRow: shouldCloseRemoveButton={this.props.shouldCloseRemoveButton}
        WishlistRow: Continues to pass the props down as above, but componentWillReceiveProps is not called here, props are not updating at this level.

1 个答案:

答案 0 :(得分:0)

我不打算将此标记为已回答,因为我想要一个真正的答案,而我为解决这个问题所做的工作对我来说还不够好。

话虽这么说,我的解决方法是移动我试图传播到react-redux的状态。使用mapDispatchToProps将redux状态设置为包含我需要的内容,然后使用mapStateToProps连接实际需要状态的组件,允许组件接收他们执行操作所需的通知。

同样,我不是选择这个作为答案 - 即使这是我为解决问题所做的事情 - 因为在某个地方还有其他可疑的东西,我想知道是否有人知道为什么事情没有按原样工作。

修改

自从这件事发生以来,我曾经遇到过这个问题。 Flatlist中存在一个prop - 这不是我在问题中使用的原始组件,但是现在不推荐使用原始组件,而Flatlist具有即将提到的此方案的支持 - 称为{{1} }。这个特殊的道具也被用来帮助Flatlist确定它是否应该重新渲染。

由于ListView已被弃用,我觉得使用Flatlist并确保传入extraData道具 - 假设你有一个不同的道具将随着列表数据的变化而改变 - 是一个可接受的答案这个问题。

相关问题