我正在使用react-intl
国际化我的react应用。我想在发送api请求时访问当前选定的语言环境以设置Accept-Language
,当前我在react组件中使用get下方的代码:
import React, { Component } from 'react';
import { intlShape, injectIntl } from "react-intl";
class CurrentLocale extends Component {
constructor(props) {
super(props);
}
render() {
const intl = this.props.intl;
return (
<p>{intl.locale}</p>
);
}
}
CurrentLocale.propTypes = {
intl: intlShape.isRequired
};
export default injectIntl(CurrentLocale);
但是我怎么能得到这样的东西?
import axios from 'axios';
import AppConfig from 'Constants/AppConfig';
// I need something like intl to use intl.locale while sending requests...
export default
axios.create({
baseURL: AppConfig.apiUrl,
timeout: 5000,
headers: {
post: {
'Content-Type': 'application/json;',
'Accept': 'application/json;',
'Accept-Language': 'fa-IR,en-US' // here i want to change this
},
get: {
'Content-Type': 'application/json;',
'Accept': 'application/json;',
'Accept-Language': 'fa-IR,en-US'// here i want to change this
}
}
});
答案 0 :(得分:0)
您可以执行以下操作:
export default intl => {
axios.create({
baseURL: AppConfig.apiUrl,
timeout: 5000,
headers: {
post: {
"Content-Type": "application/json;",
Accept: "application/json;",
"Accept-Language": intl
},
get: {
"Content-Type": "application/json;",
Accept: "application/json;",
"Accept-Language": intl
}
}
});
};
然后在您的组件中只需调用该函数即可。
class SomeComponent {
sendRequest = () => {
await send(this.props.intl);
}
}