在 React Native 中的现有状态转换期间(例如在“渲染”中)无法更新

Cannot update during an existing state transition (such as within `render`) in React Native

您好,我有一个屏幕,其中有一个条件 isProductTourCompleted 如果为真,那么我将导航到 Dashboard 屏幕。我正在尝试使用 AsyncStorage API 在 componentDidMount 方法中获取它的值。我也尝试在 componentWillMount 中更新它,但没有成功。

如果为真,则更新状态并重新渲染组件并导航至 Dashboard。它打开 Dashboard 屏幕但显示此警告。

我检查了几个有其他原因的线程。谁能提示我做错了什么?

Cannot update during an existing state transition (such as within render) in React Native

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);
  }
}

您需要检查是导航到函数上的 FirstProductTour 或 DashPage,还是从单独的容器导航。

Internally, React uses several clever techniques to minimize the number of costly DOM operations required to update the UI.
Setting a state in componentDidMount will only trigger frequent re-renders which results in bad performance optimization. Component will re render even when the props doesnt not change.

最佳解决方案:使用容器组件(或类似 ButtonClick 的函数)进行标准检查并决定导航。

另一个解决方案 将检查条件并在 componentwillMount 上调用导航功能。类似下面

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