react本机导航获取componentDidMount中的params



我正在尝试列出一些产品。我想通过导航获得categoryName作为标题,如果我把那一行放在render中,它可以工作,但我需要在componentDidMount中使用它,我该怎么做?有什么建议吗?

这是我的代码的一部分

export default class ProductList extends React.Component {
navigation = this.props.navigation;
constructor(props) {
super(props);
this.state = {
isData: false,
};
}
componentDidMount() {
const title = navigation.route.params.categoryName;  //here is my problem
fetch(global.apiPost + global.token, requestOptions)
.then((response) => response.json())
.then((result) => {
result.forEach((element) => {
if (element.Menu === title) {
products.push(element);
}
});
this.setState({isData: true});
})
.catch((error) => console.log('error', error));
}

在componentDidMount 中进行检查

componentDidMount() {
if (navigation?.route?.params?.categoryName){
const title = navigation.route.params.categoryName;  //here is my problem
fetch(global.apiPost + global.token, requestOptions)
.then((response) => response.json())
.then((result) => {
result.forEach((element) => {
if (element.Menu === title) {
products.push(element);
}
});
this.setState({isData: true});
})
.catch((error) => console.log('error', error));
}

}

最新更新