javascript - 为什么我的 ref 在 React Native 中不起作用?

标签 javascript reactjs react-native

我正在使用 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/

相关文章:

javascript - 获取浏览器中打开的所有URL

javascript - CSS 变量根伪类范围和通过 javascript 更改值

javascript - 在应用所有范围后触发的 AngularJS 事件

javascript - ReactJS 将方法绑定(bind)到类组件

reactjs - App' 指的是一个值,但在这里被用作一个类型。你的意思是 'typeof App' 吗?

reactjs - 世博会 Firebase 谷歌登录给出 : First argument "idToken" must be a valid string or a valid object or null

android - Realm 的列表属性如何工作?

javascript - 落后的 JavaScript - 优化或更便宜的功能的机会

reactjs - react 类型错误: Cannot read property 'getBoundingClientRect' of undefined

react native cli : error on start up