首页 > 解决方案 > React Little State Machine 清除数据

问题描述

带有 react-hook-form 的状态机来制作我的表单,但是在提交表单后我想在提交后清除存储;

这就是我创建商店的方式;

createStore({
  data: {}
}); 

这是我的提交功能

const onSubmit = (data:any) => {
        action(data);
        props.onSubmit(state.data);
        // I need a function to clear the data to not complete my forms after i submit
      }

这是我想要的一个小例子: https ://codesandbox.io/s/delete-data-little-state-machine-q3w0g 在“step3”中,我想在单击按钮后清除数据

标签: reactjsreact-hook-form

解决方案


看起来您需要创建另一个动作并将其传递给钩子。您可以在 docs中看到这方面的示例。这是一个工作示例

clearAction.js

export default function clearAction(state, payload) {
  return {
    data: {}
  };
}

Step3.js

import React from "react";
import { useForm } from "react-hook-form";
import { withRouter } from "react-router-dom";
import { useStateMachine } from "little-state-machine";
import clearAction from "./clearAction";

const Step3 = (props) => {
  const { register, handleSubmit } = useForm();
  const { state, action } = useStateMachine(clearAction);
  const onSubit = (data) => {
    action(data);
    props.history.push("./resultFinal");
    console.log(state, action);
    action();
  };

  return (
    <form onSubmit={handleSubmit(onSubit)}>
      <h2>Clear Data</h2>
      <input type="submit" />
    </form>
  );
};

export default withRouter(Step3);

请注意,在文档中提供的示例中,您可以根据需要将多个操作传递给钩子。


推荐阅读