我正在使用 React 16.3.0-alpha.1,我正在尝试创建一个引用来检查我的组件是否已安装,以避免出现“只能更新已安装或正在安装的组件”警告。我正在检查我的 componentDidMount 函数中的引用,但它从来没有任何引用值,因此它永远不会进入 if 语句。有谁知道应该找谁来工作 react native 吗?
constructor(props) {
super(props);
this.productCard = React.createRef();
}
componentDidMount() {
this.props.dispatch(handleLoadProduct(this.props.product.id)).then((data) => {
if (data.response && data.response.images) {
let images = data.response.images.map(img => {
return 'https://b2b.martinsmart.com/productimages/' + img.original;
});
if (this.productCard) {
this.setState({imgArray: images});
}
}
});
}
以及 View :
<View
ref={(pc) => this.productCard = pc}
style={{height: '100%', backgroundColor: '#D6D6D6'}}
>
最佳答案
您可以使用常规实例变量,而不是使用 ref
在使用 setState
之前检查组件是否仍已安装。
示例
class App extends React.Component {
mounted = true;
componentDidMount() {
this.props.dispatch(handleLoadProduct(this.props.product.id)).then(data => {
if (!this.mounted) {
return;
}
if (data.response && data.response.images) {
let images = data.response.images.map(img => {
return "https://b2b.martinsmart.com/productimages/" + img.original;
});
this.setState({ imgArray: images });
}
});
}
componentWillUnmount() {
this.mounted = false;
}
// ...
}
关于javascript - 为什么我的 ref 在 React Native 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51641112/