【问题标题】:Use ref when props is ready当 props 准备好时使用 ref
【发布时间】:2020-07-30 15:04:32
【问题描述】:
export default class Test extends Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

  componentDidMount() {
    if (this.props.data.length) {
      this.myRef.current.scrollToIndex({
        index: this.props.index,
      });
    }
  }

  render() {
    return (
      <FlatList
        ref={this.myRef}
        data={this.props.data}
        renderItem={this.renderItem}
        getItemLayout={(data, index) => ({
          length: 50,
          offset: 100 * index,
          index,
        })}
      />
    );
  }
}

目标: 一旦组件呈现,FlatList 应该自动向下滚动到具有 index === this.props.index 的项目(想象一个即时消息应用程序,您希望在其中自动向下滚动到一条消息)

问题: this.myRef 或 this.props.data 未定义。

观察:

  1. this.myRef 最早只能在componentDidMount 中使用。
  2. this.props 在 componentDidMount 中未定义,因为它需要时间 让this.props 读取使用(我的意思是ready,有值,已定义)
  3. 在getDerivedStateFromProps 中,我检查了this.props 是否已准备好,但是this.myRef 仍未定义。 (也许它初始化还为时过早)

我怎样才能实现我的目标?

System:
    OS: macOS 10.15.3
    CPU: (4) x64 Intel(R) Core(TM) i5-5257U CPU @ 2.70GHz
    Memory: 122.77 MB / 8.00 GB
    Shell: 5.7.1 - /bin/zsh
  Binaries:
    Node: 12.13.1 - ~/.nvm/versions/node/v12.13.1/bin/node
    npm: 6.12.1 - ~/.nvm/versions/node/v12.13.1/bin/npm
    Watchman: 4.9.0 - /usr/local/bin/watchman
  SDKs:
    iOS SDK:
      Platforms: iOS 13.2, DriverKit 19.0, macOS 10.15, tvOS 13.2, watchOS 6.1
    Android SDK:
      API Levels: 28, 29
      Build Tools: 28.0.3, 29.0.2
      System Images: android-28 | Google APIs Intel x86 Atom, android-29 | Google APIs Intel x86 Atom
  IDEs:
    Android Studio: 3.5 AI-191.8026.42.35.5977832
    Xcode: 11.3.1/11C504 - /usr/bin/xcodebuild
  npmPackages:
    react: 16.9.0 => 16.9.0
    react-native: https://github.com/expo/react-native/archive/sdk-36.0.1.tar.gz => 0.61.4

【问题讨论】:

  • 当道具准备好时是什么意思?
  • 准备好我的意思是,有价值,被定义
  • 您没有在代码中的任何地方定义this.myRef - 不是在收到props 之前或之后。我相信这是这里的问题
  • props 是在传递给组件时定义的,因此它们肯定是在调用 componentDidMount 时定义的。 data 是否可能是 undefined 或空数组 [] 并由父组件获取?在这种情况下,您需要使用componentDidUpdate 来处理data 更新并变为已定义或空数组以外的其他内容。这在您的“消息”示例中很有意义,因为您希望在新消息到达时滚动到底部。
  • 试试 componentDidUpdate 钩子

标签: javascript reactjs react-native react-native-flatlist ref


【解决方案1】:

componentDidMount 仅在第一次渲染后调用一次,但如果您的数据尚未准备好,那么您将没有第二次向下滚动的机会。

您应该删除您的 componentDidMount 并将其替换为 componentDidUpdate 以处理 props.data 中的更改:

componentDidUpdate(prevProps) {
    if (this.props.data !== prevProps.data) {
        if (this.props.data.length) {
            this.myRef.current.scrollToIndex({
                index: this.props.index,
            });
        }
    }
}

【讨论】:

    猜你喜欢
    • 2020-03-28
    • 2019-07-14
    • 2012-02-08
    • 2011-12-20
    • 1970-01-01
    • 2023-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多