reactjs - 使用 React 和 Redux 创建步进器
问题描述
我正在尝试使用 react 和 redux 创建一个步进器。我使用的概念是-
- 将活动步骤存储在 redux 存储中。
- 我有一个组件列表,每个组件都与一个索引相关联。
- 在父组件中,我渲染索引等于活动步骤的组件。
这是父组件的代码 -
我有组件步骤图 -
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
从父组件中的商店访问时。它反映的是以前的值而不是更新的值。
有关如何解决此问题的任何建议?任何帮助将不胜感激。提前致谢!!:)
解决方案
推荐阅读
- solr - Hybris SOLR“设备上没有剩余空间”
- jsf - 带有图像的 selectOneMenu 不显示单选按钮
- snowflake-cloud-data-platform - 从具有最小权限的视图中卸载数据
- javascript - autocomplete="new-password" 在 v-text-field 中显示旧密码的建议
- javascript - watch 函数表达式影响 Chrome devtool 中的调试
- mongodb - Mongo聚合:如何对多维数组求和
- c# - 在c#中将mm(公制)转换为英制(分数)
- angular - 面临 Highcarts.Chart 的问题
- angular - 从 TemplateRef 迭代子 TemplateRefs
- python - 根据 python 中的匹配将字符串的部分转换为新行