首页 > 解决方案 > 为什么这段代码不调用 componentDidUpdate() ?

问题描述

代码

const Index = {
  screen: IndexScreen,
  params: { category: null },
};

const IndexStack = createStackNavigator(
  {
    Index,
  },
  {
    initialRouteName: 'Index',
    navigationOptions: {
    ...
    },
  },
);
<TouchableOpacity
  onPress={() => this.props.navigation.navigate('Index', { category: 1})}
>
  <Text>Navigating to Index</Text>
</TouchableOpacity>

产品.js

async componentDidUpdate(prevProps) {
  console.log(prevProps.navigation.state.params);
}

问题

从其他组件导航到索引时,它传递一个参数:类别。

索引应该收到它,但console.log()什么componentDidUpdate()都不返回。

标签: reactjsreact-native

解决方案


在您的情况下,您应该获取导航参数componentDidMount 如您在此处看到的,在渲染componentDidUpdate触发,因此当您第一次启动此组件时它不会工作。


推荐阅读