首页 > 解决方案 > 使用 React 和 Redux 创建步进器

问题描述

我正在尝试使用 react 和 redux 创建一个步进器。我使用的概念是-

  1. 将活动步骤存储在 redux 存储中。
  2. 我有一个组件列表,每个组件都与一个索引相关联。
  3. 在父组件中,我渲染索引等于活动步骤的组件。

这是父组件的代码 -

我有组件步骤图 -

const COMPONENT_STEP_MAP = {
    1: (props) => (
        <Component1
        {...props}
        render = {(props) => <Buttons {...props}/>}
        ></Component1>
    ),
    2: (props) => (
        <Component2
        {...props}
        render = {(props) => <Buttons {...props}/>}
        ></Component2>
    ),}

这是我的 Redux 商店的样子 -

const initialState = {
  activeTab: 1,
  basicDetails: {
    activeStep: 1,
    name: '',
    }

这是父组件的渲染功能 -

 export class ParentComponent extends React.component {
        handleNext = () => {
          if(this.props.activeStep == 1 && 
         this.props.isBusinessOwner==false){ // isBusinessOwner is not showing correct value.
            this.props.setActiveStep(this.props.activeStep + 2)
          }
          else this.props.setActiveStep(this.props.activeStep + 1);
        };
          handlePrevious = () => {
            if(this.props.activeStep == 1 && 
             this.props.isBusinessOwner==false){
              this.props.setActiveStep(this.props.activeStep - 2);
            } else
            this.props.setActiveStep(this.props.activeStep - 1)
          };

       render() {
        return ({Object.entries(COMPONENT_STEP_MAP).map((comp) => {
                      return comp[0] == this.props.activeStep
                        ? comp[1]({handlePrevious, handleNext}):null}}) } }

我正在使用 react-redux 将其连接到商店 -

const mapStateToProps = (state) => ({activeStep: state.ownerDetails.activeStep, isBusinessOwner: state.ownerDetails.isBusinessOwner});
  const mapDispatchToProps = (dispatch) => ({
    setActiveStep: (step) => dispatch({type: 'ownerDetails', payload:{activeStep: step}})
  })

  export default connect(mapStateToProps, mapDispatchToProps)(OwnerDetails);

现在我有以下子组件

import React from 'react';
import {useSelector, useDispatch} from 'react-redux';

export function IsOwner(props) {
    const isOwner = useSelector(state => state.ownerDetails.isBusinessOwner);
    const setIsBusinessOwner = useDispatch();
    const handleChange = (value) => {
        // console.log('value', value);
        setIsBusinessOwner({type: 'ownerDetails', payload: {isBusinessOwner: value}})
        props.handleNext();
    };
    return (
        <div>
            <h4>Are You Business Owner</h4>
            <button onClick={handleChange.bind(null,true)}>Yes</button>
            <button onClick={handleChange.bind(null,false)}>No</button>
        </div>
    )
}

我对以下两行有疑问-

setIsBusinessOwner({type: 'ownerDetails', payload: {isBusinessOwner: value}})
props.handleNext();

setIsBusinessOwner更新存储并强制组件重新渲染。 但是,我立即调用props.handleNext()它,组件将从 DOM 中消失。

因此,当我isBusinessOwner从父组件中的商店访问时。它反映的是以前的值而不是更新的值。

有关如何解决此问题的任何建议?任何帮助将不胜感激。提前致谢!!:)

标签: reactjsreduxreact-reduxfrontend

解决方案


推荐阅读