2017-01-23 115 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

相關問題