React國際化——多語言切換
1.安裝react-intl-universal:npm install react-intl-universal --save
2.配置語言包,json檔案根據需要支援幾種語言決定(將新建的語言包json檔案放置於專案根目錄的./public/locales下):
3.引入react-intl-universal:import intl from "react-intl-universal";
引入axios:import axios from 'axios';
4.核心程式碼:
const SUPPOER_LOCALES = [
{
name: "中文",
value: "zh-CN"
},
{
name: "English",
value: "en-US"
},
];
class App extends React.Component {
state = {
initDone: false,
language: "zh-CN",
}
componentDidMount() {
this.loadLocales(this.state.language);
}
loadLocales(val) {
let currentLocale = val
axios.get(`locales/${currentLocale}.json`)
.then(res => {
console.log("App locale data", res.data);
// Init方法將根據當前的本地資料載入本地資料
return intl.init({
currentLocale,
locales: {
[currentLocale]: res.data
}
});
})
.then(() => {
// 在載入locale資料後,開始呈現
this.setState({ initDone: true });
});
}
}