【问题标题】:Why is my ref not working in React Native?为什么我的 ref 在 React Native 中不起作用?
【发布时间】:2018-08-02 04:04:02
【问题描述】:

我正在使用 react 16.3.0-alpha.1 并且我正在尝试创建一个 ref 以检查我的组件是否已安装以避免“只能更新已安装或正在安装的组件”警告。我正在检查我的 componentDidMount 函数中的 ref,但它对 ref 没有任何价值,因此它永远不会进入 if 语句。有谁知道让 ref 工作的人反应原生吗?

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
  ref={(pc) => this.productCard = pc}
  style={{height: '100%', backgroundColor: '#D6D6D6'}}
>

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    您可以使用常规实例变量,而不是使用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;
      }
    
      // ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-11
      • 2022-08-08
      • 1970-01-01
      • 1970-01-01
      • 2016-12-25
      • 2016-08-09
      相关资源
      最近更新 更多