2017-01-23 186 views
0

我有一个React Native组件,一旦它知道它是多大,它就会更新它的状态。 例子:React Native:在onLayout中更新状态给出了“警告:setState(...):无法在现有状态转换期间更新”

class MyComponent extends Component { 
    ... 

    render() { 
     ... 

     return (
      <View onLayout={this.onLayout.bind(this)}> 
       <Image source={this.state.imageSource} /> 
      </View> 
     ); 
    } 

    onLayout(event) { 
     ... 

     this.setState({ 
      imageSource: newImageSource 
     }); 
    } 

    ... 
} 

这提供了以下错误:

Warning: setState(...): Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount .

我猜,同时仍呈现onLayout函数被调用(这可能是不错的,更新越快越好)。解决这个问题的正确方法是什么?

在此先感谢!

回答

1

我们通过使用度量函数来解决这个问题,您必须等待场景完全完成后再进行测量,以防止出现错误值(即在componentDidMount/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}}/> 
 
); 
 
}

0

Here是从文档的解决方案对于这种情况

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 
    } 

    ... 
} 

但我认为这是更好地做这样的事情onload

相关问题