为什么我的裁判在React Native中不起作用?

时间:2018-08-01 19:37:54

标签: javascript reactjs react-native

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

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'}}
>

1 个答案:

答案 0 :(得分:2)

您可以使用常规实例变量来代替使用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;
  }

  // ...
}
相关问题