首页 > 解决方案 > 组件的构造函数第二次不工作

问题描述

我有一个组件类:

class AutoPage extends Component {
constructor(props) {
    super(props);
    console.log("Auto is " + this.props.route.params.auto);
    this.state = {
        avto: this.props.route.params.auto,
    }
    this.array = [
        this.state.avto.PICTURE,
    ];

    for (let dopImage of this.state.avto.DOP_FOTO.VALUE) {
        this.array.push(dopImage);
        //console.log(avto);
    }
    }
}

我从另一个地方打开这个组件:

<TouchableOpacity onPress={() => navigate('AutoPage', {
                auto: item
              })}>

这是我的抽屉导航:

 <Drawer.Navigator drawerContent={props => <CustomSidebarMenu {...props} />} width={Dimensions.get('window').width - 130}
  component={CustomSidebarMenu}>
  <Stack.Screen name="AutoListPage" component={AvtoListPageNav} />
  <Stack.Screen name="AutoPage" component={AutoPage} options={{ headerTitle: "GorodAvtoPrime", headerTitleAlign: "center" }} /> 
</Drawer.Navigator>

当我单击TouchableOpacity AutoPage打开时,它的构造函数工作。但是当返回并TouchableOpacity再次单击时,AutoPage 会打开并且其构造函数不起作用。我正在获取以前的数据this.props.route.params.autoAutoPage每次单击时如何运行构造函数TouchableOpacity

标签: react-nativereact-navigationreact-navigation-drawer

解决方案


您可能想要订阅focus导航事件。屏幕正在重复使用,因此不会再次创建。

https://reactnavigation.org/docs/navigation-events

class AutoPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
        avto: null,
    }
  }

  componentDidMount() {
    this._unsubscribe = this.props.navigation.addListener('focus', () => {
      // Update your state here
    });
  }

  componentWillUnmount() {
    this._unsubscribe();
  }
}

推荐阅读