【发布时间】:2019-08-15 15:28:54
【问题描述】:
我将 axios 用于 Web 请求,并为其创建了一个拦截器,以显示所有错误消息的烤面包机。
我正在使用 react-intl 进行翻译,并且拦截器中存在的通用错误消息已被翻译,因此我将拦截器与我的应用程序的生命周期联系起来:
class Main extends React.Component {
componentDidMount () {
// addToastInterceptor calls back for a message that can be evaluated dynamically
// otherwise it uses axios.interceptors.response.use(...)
this.interceptor = addToastInterceptor((e) =>
this.props.intl.formatMessage({
id: 'applicationForm.basic.errorMessage'
}, {
technicalMessage: e.message
}));
}
componentWillUnmount () {
// the interceptor handle is removed when the component unmounts
removeToastInterceptor(this.interceptor);
}
render() {
// any number of child component in any depth
}
}
// The intl provider must exist in a wrapper component
export default injectIntl(Main);
这样在挂载Main组件时,任何收到错误响应的axios调用都会触发toast消息。
我的问题如下。如果我在调用 Main.componentDidMount 之前尝试使用 axios 进行调用,则消息不会显示。
如果我在后代组件的componentDidMount 中进行调用,它不会显示消息:
// This component dispatches a redux call that uses axios.get internally
class SomeChild extends React.Component {
componentDidMount () {
// this is
this.props.getCountriesAction();
}
}
const mapStateToProps = state => ({
countries: state.boarding.countries,
});
const mapDispatchToProps = dispatch => bindActionCreators({
getCountriesAction: getCountries,
}, dispatch);
export default connect(
mapStateToProps,
mapDispatchToProps,
)(SomeChild);
一种解决方法是使用 Main 的构造函数(或 componentWillMoount)来注册拦截器,但这不会支持异步渲染,因为这些方法不能保证只运行一次。
我能否以某种方式更改 2 个 componentDidMount 调用的顺序或为此使用任何其他生命周期方法?
【问题讨论】: