为澄清起见,我是react-redux概念的新手。我尝试在演示文稿中分派一个异步操作。但这似乎无法解决。
const store = configureStore();
const Root: React.FC = () => (
<Provider store={store}>
<App />
</Provider>
);
render(<Root/>, document.getElementById('root'));
interface AppProps {
system: SystemState,
updateSession: typeof updateSession,
getLanguageThunk: any
}
const App: React.FC<AppProps> = ({system, updateSession, getLanguageThunk}) => {
useEffect(() => {
getLanguageThunk().then((res: any) => {
console.log(res);
i18n.init().then(
() => i18n.changeLanguage(res.language));
});
}, []
);
return (
<div>
<div className="app">
<TabBar/>
</div>
</div>
);
};
const mapStateToProps = (state: AppState) => ({
system: state.system
});
export default connect(mapStateToProps, { updateSession, getLanguageThunk })(App);
但是控制台每次都记录未定义的内容。所以我在这里做错了。也许您的某些人可以在这里帮助我。
export const getLanguageThunk = (): ThunkAction<void, AppState, null, Action<string>> => async dispatch => {
const language = await getLanguage();
dispatch(
updateSession({
disableSwipe: false,
language
})
)
};
async function getLanguage() {
try {
const response = await fetch('http://localhost:3000/language');
return response.json();
} catch {
return { language: 'en_GB' }
}
}
答案 0 :(得分:2)
您需要从getLanguageThunk
返回语言,才能在useEffect
方法中通过诺言使用该语言
export const getLanguageThunk = (): ThunkAction<void, AppState, null, Action<string>> => async dispatch => {
const language = await getLanguage();
dispatch(
updateSession({
disableSwipe: false,
language
})
)
return language;
};