React Redux-使用React钩子调度动作

时间:2019-05-29 06:11:50

标签: reactjs redux react-redux react-hooks

为澄清起见,我是react-redux概念的新手。我尝试在演示文稿中分派一个异步操作。但这似乎无法解决。

容器组件

const store = configureStore();

const Root: React.FC = () => (
    <Provider store={store}>
        <App />
    </Provider>
);

render(<Root/>, document.getElementById('root'));

Presentational组件

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);

但是控制台每次都记录未定义的内容。所以我在这里做错了。也许您的某些人可以在这里帮助我。

Redux中间件

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' }
    }
}

1 个答案:

答案 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;
};