代码之家  ›  专栏  ›  技术社区  ›  MarcoLe

React Redux-使用React Hooks执行调度操作

  •  1
  • MarcoLe  · 技术社区  · 6 年前

    为了清楚起见,我对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);
    

    但是控制台每次日志都没有定义。所以我在这里做错了什么。也许你们中的一些人能在这帮我。

    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 回复  |  直到 6 年前
        1
  •  2
  •   Shubham Khatri    6 年前

    您需要从返回语言 getLanguageThunk ,以便在 useEffect 方法

    export const getLanguageThunk = (): ThunkAction<void, AppState, null, Action<string>> => async dispatch => {
        const language = await getLanguage();
        dispatch(
            updateSession({
                disableSwipe: false,
                language
            })
        )
        return language;
    };