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

4

1 回答 1

1

componentWillReceiveProps仅在组件道具更新时触发,而不是在初始渲染时触发。正如文件所述,

React 在挂载期间不会使用初始道具调用 UNSAFE_componentWillReceiveProps()。如果组件的某些道具可能会更新,它只会调用此方法。调用 this.setState() 通常不会触发 UNSAFE_componentWillReceiveProps()。

componentWillReceiveProps已弃用,尤其是因为它经常被滥用。对于异步操作componentDidMountcomponentDidUpdate应该使用 and 代替componentWillMountand componentWillReceiveProps

如果您需要执行副作用(例如,数据获取或动画)以响应道具的变化,请改用 componentDidUpdate 生命周期。

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

componentDidMount() {
    this.getQuestions();
}

componentDidUpdate() {
    this.getQuestions();
}

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

    axios.get(`http://${IP_ADDRESS}/api/questions`)
    ...
}
于 2018-11-07T09:15:52.407 回答