createContext和useReducer-我需要将异步数据作为初始状态传递给useReducer,并将其传递给我的提供者

时间:2020-07-02 18:56:30

标签: reactjs react-hooks

我有问题。我需要在useReducer中将versionHistoryContext用作初始状态,然后将其传递给我的Provider。我不知道该怎么做。 我正在使用类型脚本。我TAKS是双组份我有一个按钮来选择,并且当选择了一些选项我的版本或previe版本组件重新渲染

import React, { useReducer, useState } from 'react';
import { useParams } from 'react-router-dom';

// api
import { getArticleVersion, getListOfArticleVersions } from 'content/api';
// types

import { IField, IVersionHistoryContext, VersionItem } from 'content/types/types';

// providers
import { ContentVersionProvider } from 'content/providers/contentVersion.provider';

// components
import VersionPreview from './VersionPreview';
import Version from './Vesrion';

interface IProps {
}

const ContentTopbarVersionsHistory: React.FC<IProps> = (props: IProps) => {
    const [versionHistoryContext, setVersionHistoryContext] = useState<Partial<IVersionHistoryContext>>({});
    const { id } = useParams();

    const getArticleVersionDataOnInit = async (articleId: number): Promise<void> => {
        const fields: Array<IField> = await getArticleVersion(id);
        console.log('versionHistoryContext', versionHistoryContext);
        setVersionHistoryContext({
            ...versionHistoryContext,
            previewContent: {
                id: articleId,
                fields,
                loading: false,
            },
            editContent: {
                id: articleId,
                fields,
                loading: false,
            },
        });
    };

    const getListOfVersions = async (): Promise<void> => {
        const versionList: Array<VersionItem> = await getListOfArticleVersions(id);
        setVersionHistoryContext({
            ...versionHistoryContext,
            versionList,
            editContent: {
                loading: true,
            },
            previewContent: {
                loading: true,
            },
        });
    };

    React.useEffect(() => {
        getListOfVersions();
    }, []);

    React.useEffect(() => {
        if (versionHistoryContext.versionList && versionHistoryContext.versionList.length > 0) {
            const firstEl: VersionItem = versionHistoryContext.versionList[0];
            getArticleVersionDataOnInit(firstEl.id);
        }
    }, [versionHistoryContext.versionList]);

    return (
        <ContentVersionProvider value={versionHistoryContext}>
            <div className="row">
                <div className="col-6 p-0">
                    <VersionPreview />
                </div>
                <div className="col-6 p-0">
                    <Version />
                </div>
            </div>
        </ContentVersionProvider>
    );
};

export default ContentTopbarVersionsHistory;

0 个答案:

没有答案