当我们在堆栈导航器组件之间导航时,未调用ComponentWillReceiveProps吗?

时间:2018-11-07 09:00:37

标签: reactjs react-native react-navigation react-navigation-stack

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吗?

1 个答案:

答案 0 :(得分:0)

componentWillReceiveProps仅在组件属性更新时触发,而不是在初始渲染时触发。如the documentation所述,

  

在安装过程中,React不会使用初始道具调用UNSAFE_componentWillReceiveProps()。仅当某些组件的道具可能会更新时才调用此方法。通常,调用this.setState()不会触发UNSAFE_componentWillReceiveProps()。

componentWillReceiveProps已过时,特别是因为它经常被滥用。对于异步操作,应该使用componentDidMountcomponentDidUpdate代替componentWillMountcomponentWillReceiveProps

  

如果您需要因道具更改而产生副作用(例如,数据获取或动画),请改用componentDidUpdate生命周期。

如果两个钩子都适用相同的逻辑,则应该有一种可重用的方法。已经有这种方法,getQuestions

componentDidMount() {
    this.getQuestions();
}

componentDidUpdate() {
    this.getQuestions();
}

getQuestions() {
    this.setState({ isLoading: true, questions: [] });

    axios.get(`http://${IP_ADDRESS}/api/questions`)
    ...
}