清除小状态机中的存储

clear store in little-state-machine

我正在使用 little-state-machine (https://github.com/bluebill1049/little-state-machine) with react-router for a wizard on a client's site and I need to reset the store when a user returns to the wizard landing page. I followed this answer in stack overflow (),但我无法使用它。我不能展示完整的应用程序,但是从下面你能看出我所做的有什么问题吗?

App.js

createStore({
  data
});

function App() {
  
    return (
      <StateMachineProvider>
        <DevTool />
        <div className="container">
          ...
          <Router>
            <Steps />
          </Router>
        </div>
      </StateMachineProvider>
    );
  }

  export default App;
  

Steps.js

....
import { useStateMachine } from "little-state-machine";
import clearAction from "./lsm/actions/clearAction";
...

export default () => {
    ....
   const location = useLocation();
   const { state, actions } = useStateMachine({ clearAction });
   ...
   
   useEffect(() => {
   
       let step = location.pathname.split("/")[2];
       // landing page location = http://site.co.uk/wizard
       // steps have url = http://site.co.uk/wizard/step[1-4]
       if(!step){
     
           actions.clearAction();
   
       }

   }, []);

return (...);
};

clearAction.js

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

从我所看到的你分享的代码片段来看,这个 Steps 组件可能正在渲染一个 Route 或一组 Route 对应的到向导步骤。如果我了解您的 question/issue,您希望在步骤为 0 或某个虚假值时随时重置向导。

问题是 Steps 仅在安装时运行此检查一次。要解决此问题,您可以将 location 对象作为依赖项添加到 useEffect 挂钩,以便在 location 更改时触发挂钩的回调。 step 条件将检查是否在向导登录页面上并重置状态机。

export default () => {
  ....
  const location = useLocation();
  const { state, actions } = useStateMachine({ clearAction });
  ...
   
  useEffect(() => { 
    let step = location.pathname.split("/")[2];
    // landing page location = http://site.co.uk/wizard
    // steps have url = http://site.co.uk/wizard/step[1-4]
    if (!step) {
      actions.clearAction();
    }
  }, [location]); // <-- add location as a dependency

  return (...);
};