历史记录和状态重置

发布于 2025-02-07 04:14:38 字数 1791 浏览 1 评论 0原文

使用props.history.push步骤表单使我的状态弄乱了。我有一个多步骤形式,并将当前步骤保持在组件状态。此外,在步骤之间,我需要更改同一组件中的URL,因此我有一个条件路由。在下一个和上一个之间,我正在调用一个函数以更新当前步骤,当前步骤计数器在单击步骤时就像魅力一样工作。当需要更改URL时,问题出现。

使用props.history.push(路由)正在重新渲染组件,并且当前的步骤计数器丢失并将其设置回0(其初始值)。我如何避免在该州放松柜台?代码片段如下:

const StepForm = (props, state, next, prev,) => [
  {
    title: "Step 1",
    content: <StepOne />,
    buttons: [
      null,
      <Button onClick={() => next_step()}> Next </Button>,
    ],
  },
  {
    title: "Step 2",
    content: (<stepTwo/>),
    buttons: [
      <Button
        onClick={() => {
          next_step(); //Somehow this does not execute in this step. If
          props.history.push( // I remove history.push, the state is kept
            `/items/${item.id}`
          );
        }}
      >
        Next
      </Button>,
    ],
  },
  {
    title: "Step 3",
    content: <StepThree />,
    buttons: [
      null,
      <Button onClick={() => next_step()}> Done </Button>,
    ],
  },
];


export class ItemPage extends Component {
  state = {
    step: 0,
  };
  
  next_step = () => this.setState((prevState) => ({ step: prevState.step + 1 }));
  prev_step = () => this.setState((prevState) => ({ step: prevState.step - 1 }));
  
  render() {
    const Forms = StepForms(
      this.props,
      this.state,
      this.next_step,
      this.prev_step);
    
    <Steps step={this.state.step}>
       {Forms.map((step) => (
         <Steps.Step key={step.title} title={step.title} />
       ))}
    </Steps>
    <Col span={24}>
      <div>{Forms[this.state.step].content}</div>
    </Col>

问题是组件是用props.history.push()重新渲染的,并且状态中的步骤变量已重置为0。我应该如何避免重置状态?

谢谢

Using props.history.push step forms is messing up my state. I have a mult-step form and keep the current step in the state of the component. In addition, between steps I need to change the URL in the same component, so I have a conditional route working. In between next and previous I am calling a function to update the current step, the current step counter is working like a charm when clicking through the steps. The issue comes when needing to change the URL.

Using props.history.push(route) is re-rendering the component and the current step counter is lost and set back to 0 (its initial value). How can I avoid to loose the counter in the state? The code snippet is the following:

const StepForm = (props, state, next, prev,) => [
  {
    title: "Step 1",
    content: <StepOne />,
    buttons: [
      null,
      <Button onClick={() => next_step()}> Next </Button>,
    ],
  },
  {
    title: "Step 2",
    content: (<stepTwo/>),
    buttons: [
      <Button
        onClick={() => {
          next_step(); //Somehow this does not execute in this step. If
          props.history.push( // I remove history.push, the state is kept
            `/items/${item.id}`
          );
        }}
      >
        Next
      </Button>,
    ],
  },
  {
    title: "Step 3",
    content: <StepThree />,
    buttons: [
      null,
      <Button onClick={() => next_step()}> Done </Button>,
    ],
  },
];


export class ItemPage extends Component {
  state = {
    step: 0,
  };
  
  next_step = () => this.setState((prevState) => ({ step: prevState.step + 1 }));
  prev_step = () => this.setState((prevState) => ({ step: prevState.step - 1 }));
  
  render() {
    const Forms = StepForms(
      this.props,
      this.state,
      this.next_step,
      this.prev_step);
    
    <Steps step={this.state.step}>
       {Forms.map((step) => (
         <Steps.Step key={step.title} title={step.title} />
       ))}
    </Steps>
    <Col span={24}>
      <div>{Forms[this.state.step].content}</div>
    </Col>

The issue is that component is re-render with props.history.push(), and step variable in state is reset to 0. How should I avoid resetting state?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

找个人就嫁了吧 2025-02-14 04:14:38

使用简单的redux的问题是,每当发生刷新时,所有状态都会丢失。可以使用 redux-persist 。该库是为了克服这个问题而开发的。通过与redux一起使用此库。即使发生URL更改或刷新,它也可以保存您的状态。它基本上是一种类型。浏览器中的本地存储。它易于设置。

它基本上将PersistreDucer和PersistStore添加到您的设置中。这使状态即使在刷新中也可以保存。
您需要做的就是。
在app.js中使用这样的persist Gate将您的应用程序结束

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import store from './app/store';
import { Provider } from 'react-redux';
import * as serviceWorker from './serviceWorker';
import { PersistGate } from 'redux-persist/integration/react';
import { persistStore } from 'redux-persist';

let persistor = persistStore(store);

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
          <App/>
      </PersistGate>
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);
serviceWorker.unregister();

然后在store.js

import { configureStore } from '@reduxjs/toolkit';
import storage from 'redux-persist/lib/storage';
import { combineReducers } from 'redux';
import { persistReducer } from 'redux-persist';
import thunk from 'redux-thunk';

import counterReducer from '../features/counter/counterSlice';

const reducers = combineReducers({
  counter: counterReducer,
});

const persistConfig = {
  key: 'root',
  storage,
};

const persistedReducer = persistReducer(persistConfig, reducers);

const store = configureStore({
  reducer: persistedReducer,
  devTools: process.env.NODE_ENV !== 'production',
  middleware: [thunk],
});

export default store;

通过这种方式,您可以轻松地添加redux持续存在以保存状态。这将解决您的问题。谢谢。

这是一篇完整的详细文章。
使用redux-persist with redux

The problem with using simple redux is that whenever a refresh occurs,all the states are lost.This problem can be easily resolved using redux-persist.This library was developed to overcome this problem.By using this along with redux.It will make your state saved even when a url changes or a refresh occurs.It basically is a type of local storage in the browser.It is easy to setup.

It basically adds persistReducer and persistStore to your setup.Thats makes the state to be saved even on a refresh.
All you need to do is.
Wrap up your app with persist gate like this in App.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import store from './app/store';
import { Provider } from 'react-redux';
import * as serviceWorker from './serviceWorker';
import { PersistGate } from 'redux-persist/integration/react';
import { persistStore } from 'redux-persist';

let persistor = persistStore(store);

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
          <App/>
      </PersistGate>
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);
serviceWorker.unregister();

Then in store.js

import { configureStore } from '@reduxjs/toolkit';
import storage from 'redux-persist/lib/storage';
import { combineReducers } from 'redux';
import { persistReducer } from 'redux-persist';
import thunk from 'redux-thunk';

import counterReducer from '../features/counter/counterSlice';

const reducers = combineReducers({
  counter: counterReducer,
});

const persistConfig = {
  key: 'root',
  storage,
};

const persistedReducer = persistReducer(persistConfig, reducers);

const store = configureStore({
  reducer: persistedReducer,
  devTools: process.env.NODE_ENV !== 'production',
  middleware: [thunk],
});

export default store;

In this way you can easily add redux persist to save your state permenanyly.This will resolve your problem.Thanks.

Here is a complete detailed article for it.
Using redux-persist with redux

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文