export default (DrawNav = createStackNavigator(
{
Home: { screen: Home },
QuestionDetail: { screen: QuestionDetail },
QuestionAsk: { screen: QuestionAsk }
},
{
initialRouteName: "Home",
headerMode: "none"
}
));
Home组件列出了问题,而QuestionDetail显示了问题的详细信息,但这是我面临的问题,每当您从QuestionDetail或其他组件返回家中时,我都想抓住问题,这就是我在Home组件中所做的事情,
componentDidMount() {
this.getQuestions();
}
componentWillReceiveProps() {
this.setState({ questions: [] }, () => {
this.getQuestions();
});
}
getQuestions() {
this.setState({ isLoading: true });
axios.get(`http://${IP_ADDRESS}/api/questions`)
.then(response => {
console.log('response data: ', response.data);
this.setState({ questions: response.data, isLoading: false })
})
.catch((err) => {
this.setState({ isLoading: false });
console.log('QUESTIONS ERR: '+err);
// this.props.history.push('/');
})
}
但是当您从QuestionDetail导航到Home时,未调用componentWillReceiveProps吗?
答案 0 :(得分:0)
componentWillReceiveProps
仅在组件属性更新时触发,而不是在初始渲染时触发。如the documentation所述,
在安装过程中,React不会使用初始道具调用UNSAFE_componentWillReceiveProps()。仅当某些组件的道具可能会更新时才调用此方法。通常,调用this.setState()不会触发UNSAFE_componentWillReceiveProps()。
componentWillReceiveProps
已过时,特别是因为它经常被滥用。对于异步操作,应该使用componentDidMount
和componentDidUpdate
代替componentWillMount
和componentWillReceiveProps
:
如果您需要因道具更改而产生副作用(例如,数据获取或动画),请改用componentDidUpdate生命周期。
如果两个钩子都适用相同的逻辑,则应该有一种可重用的方法。已经有这种方法,getQuestions
:
componentDidMount() {
this.getQuestions();
}
componentDidUpdate() {
this.getQuestions();
}
getQuestions() {
this.setState({ isLoading: true, questions: [] });
axios.get(`http://${IP_ADDRESS}/api/questions`)
...
}