【发布时间】: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 未定义。
观察:
-
this.myRef最早只能在componentDidMount中使用。 -
this.props在componentDidMount中未定义,因为它需要时间 让this.props读取使用(我的意思是ready,有值,已定义) - 在
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