react-admin v3迁移:非组件环境下如何替换changeLocale实现多语言切换?
Got it, let's fix this migration issue. React Admin v3 did refactor its i18n system to prefer hooks, but we can still make this work in redux-saga without relying on component hooks. Here's how:
Step-by-Step Fix
Update the Action Creator Import
React Admin v3 replacedchangeLocalewithsetLocaleas the official action creator for updating the locale. This is the main reason your old code stopped working.Keep Using Redux-Saga Logic
Even though hooks are the new recommended approach, React Admin still manages locale state in the Redux store under the hood. Dispatching thesetLocaleaction directly from your saga will still update the locale correctly.Add Error Handling (Optional but Recommended)
WrappingJSON.parsein a try/catch prevents unexpected crashes if theauthenticateditem in localStorage is corrupted or invalid.
Corrected Code
import { USER_LOGIN_SUCCESS, USER_CHECK, USER_CHECK_SUCCESS, setLocale } from "react-admin"; import { takeEvery, put } from "redux-saga/effects"; export default function* authSagas() { // takeEvery is still fully supported in redux-saga v1.x – no need to worry about deprecation here yield takeEvery(USER_LOGIN_SUCCESS, handleLanguage); yield takeEvery(USER_CHECK, handleLanguage); yield takeEvery(USER_CHECK_SUCCESS, handleLanguage); } export function* handleLanguage(action) { const authenticatedData = localStorage.getItem('authenticated'); if (!authenticatedData) { return; } try { const user = JSON.parse(authenticatedData); if (user.locale) { yield put(setLocale(user.locale)); } } catch (error) { console.error('Failed to parse user authentication data:', error); // You can add additional error handling here if needed } }
Key Notes
- Why This Works: React Admin's
useSetLocalehook actually dispatches thesetLocaleaction under the hood, so calling it directly from your saga has the same effect. - Redux-Saga's
takeEvery: This helper is not deprecated or removed in redux-saga v1.0.0 – it's still the standard way to handle repeated actions like login success or user check events. - Fallback Option: If for some reason
setLocaledoesn't work (unlikely), you can manually dispatch the action:
But using the official action creator is always better for future compatibility.yield put({ type: 'SET_LOCALE', payload: user.locale });
内容的提问来源于stack exchange,提问作者Armel Larcier

