0

嗨現有狀態轉移(如內`render`)期間無法更新我有一個屏幕,在這裏我有isProductTourCompleted如果真的話,我要前往Dashboard屏幕的條件。我正在嘗試使用AsyncStorage API在componentDidMount方法中獲得它的價值。我也嘗試在componentWillMount更新它,但沒有運氣。在陣營本地

如果這是真的,則在更新狀態,並重新呈現組件並導航到Dashboard。它打開Dashboard屏幕但顯示此警告。

我檢查了其它一些原因,幾個線程。任何人都可以提示我我做錯了什麼?

現有狀態轉移(如render內)的陣營本地

export default class FirstProductTour extends Component { 
    constructor(props) { 
    super(props); 
    this._startDashboardScreen = this._startDashboardScreen.bind(this); 

    this.state = { 
     isProductTourCompleted: false 
    }; 
    } 

    componentDidMount() { 
    AsyncStorage.getItem("@ProductTour:key").then(value => { 
     if (value) 
     this.setState({ 
      isProductTourCompleted: true 
     }); 
    }); 
    } 

    render() { 
    const { navigate } = this.props.navigation; 

    return (
     <View style={styles.container}> 
     {this.state.isProductTourCompleted 
      ? this._startDashboardScreen() 
      : <View style={styles.container}> 
       <Image source={require("../../img/talk_people.png")} /> 
       <Text style={styles.centerAlignTextStyle}> 
       {strings.talk_people} 
       </Text> 

       <RoundButton 
       robotoThinStyle={styles.roundButtonStyle} 
       centerAlignTextStyle={styles.whiteColorStyle} 
       onPress={() => { 
        const resetAction = NavigationActions.reset({ 
        index: 0, 
        actions: [ 
         NavigationActions.navigate({ 
         routeName: "SecondProductTour" 
         }) 
        ] 
        }); 
        this.props.navigation.dispatch(resetAction); 
       }} 
       > 
       {strings.continueText} 
       </RoundButton> 
      </View>} 
     </View> 
    ); 
    } 

    _startDashboardScreen() { 
    const resetAction = NavigationActions.reset({ 
     index: 0, 
     actions: [ 
     NavigationActions.navigate({ 
      routeName: "Dashboard" 
     }) 
     ] 
    }); 
    this.props.navigation.dispatch(resetAction); 
    } 
} 

enter image description here

+1

你需要檢查是否導航到FirstProductTour或DashPage函數或從一個單獨的容器。你不能在渲染上檢查它,因爲這會導致錯誤。嘗試調用ComponentDidMount上的導航而不是設置狀態。 – Vicky

+1

@vicky是正確的。如果productTourCompleted爲true,則不會顯示您正在更改狀態/視圖,因此如果您只想導航到不同的屏幕,則無需重新渲染。而不是你的ComponentDidMount中的setState,在那裏調用你的導航。 – basudz

+1

看起來像它的工作:) @Vicky你們可以用一些細節回答所以它會爲未來的讀者是太有用並接受它:) –

回答

3

你需要檢查是否導航到FirstProductTour或DashPage上時,無法更新功能或從一個單獨的容器。

在內部,React使用多種巧妙的技術來最小化更新UI所需的昂貴DOM操作的數量。
componentDidMount設置的狀態只會觸發頻繁的重新渲染,這會導致糟糕的性能優化。即使道具沒有改變,組件也會重新渲染。

最佳解決方案:使用不標準檢查和判定導航容器組件(或類似ButtonClick的函數)。

另一個解決方案將檢查條件並調用componentwillMount上的導航功能。像下面的東西

componentDidMount() { 
    AsyncStorage.getItem("@ProductTour:key").then(value => { 
     if (value) 
     this._startDashboardScreen() 
    }); 
    }