かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

React + TypeScriptでredux-formのformの値を初期化する

redux-formのformになるクラスにinitialValuesというプロパティに値を設定してやると、フォームデータが初期化されるくさい。

注意点としては、redux-formの型定義ファイルにinitialValuesが定義されてないので自分でプロパティをはやしてやる必要があるという点です。

interface FormData {
    lhsField: string;
    rhsField: string;
}

interface IndexPageProps extends ReduxForm.ReduxFormProps {
    lhs?: number;
    rhs?: number;
    answer?: number;
    initialValues?: FormData; // 自分ではやす
    init?: () => void;
}

あとは、reduxForm関数に渡すselect関数でinitialValuesを適当にstateから抜き出してやればOK。

function select(state: rootReducers.AppState): IndexPageProps {
    return {
        lhs: state.calc.lhs,
        rhs: state.calc.rhs,
        answer: state.calc.answer,
        initialValues: {
            lhsField: state.calc.lhs && state.calc.lhs.toString(),
            rhsField: state.calc.rhs && state.calc.rhs.toString()
        }
    };
}

export default ReduxForm.reduxForm({
    form: 'IndexForm',
    fields: ['lhsField', 'rhsField']
}, select, {
    init: calcActions.init
})(IndexPage);

ソース全体

GitHubに上げておきました

github.com