React Native:在 onLayout 中更新状态会"Warning: setState(...): Cannot update during an existing state transi



我在 React Native 中有一个组件,一旦知道它的大小,它就会更新它的状态。例:

class MyComponent extends Component {
    ...
    render() {
        ...
        return (
            <View onLayout={this.onLayout.bind(this)}>
                <Image source={this.state.imageSource} />
            </View>
        );
    }
    onLayout(event) {
        ...
        this.setState({
            imageSource: newImageSource
        });
    }
    ...
}

这将给出以下错误:

警告:setState(...):在现有状态转换期间(例如在render或其他组件的构造函数中)无法更新。渲染方法应该是道具和状态的纯函数;构造函数的副作用是一种反模式,但可以移动到componentWillMount

我想在仍然渲染时调用 onLayout 函数(这可能很好,更新越早越好)。解决这个问题的正确方法是什么?

提前感谢!

我们通过使用测量功能解决了这个问题,您必须等到场景完全完成才能进行测量以防止不正确的值(即在组件DidMount/componentDidUpdate中)。下面是一个示例:

  measureComponent = () => {
    if (this.refs.exampleRef) {
      this.refs.exampleRef.measure(this._logLargestSize);
    }
  }
  _logLargestSize = (ox, oy, width, height, px, py) => {
    if (height > this.state.measureState) {
      this.setState({measureState:height});
    }
  }
render() {
  return (
    <View ref = 'exampleRef' style = {{minHeight:  this.props.minFeedbackSize}}/>
  );
}

这是针对此类情况的文档的解决方案

class MyComponent extends Component {
...
  render() {
    ...
    return (
        <View>
            <Image ref="image" source={this.state.imageSource} />
        </View>
    );
  }
  componentDidMount() {
    //Now you can get your component from this.refs.image
  }
  ...
}

但在我看来,最好在负载上做这样的事情

相关内容

最新更新