【发布时间】:2021-04-01 22:59:09
【问题描述】:
依赖项
“反应”:“^17.0.1”
"react-redux": "^7.2.2"
我有一个包含几个步骤的注册页面,每个步骤都有不同的形式。我根据 url 中的段更改了表单。因此,我想通过将其存储到减速器来跟踪步骤进度,但它仅在第一个表单加载时才起作用(这是默认表单)。
在history.push()之后触发SecondStep表单导致reducer状态丢失的下一步
父组件
import React from "react";
import { useSelector } from 'react-redux';
import FirstStep from './FirstStep';
import SecondStep from './SecondStep';
export default function Register({
url
}) {
const { stepTracker } = useSelector(state => state.registrationReducer)
const segment = url.substring(url.lastIndexOf('/') + 1);
console.log(stepTracker)
function renderForm(){
var tpl = (<FirstStep url={url} />)
if(segment === 'register'){
tpl = (<FirstStep url={url} />)
}
if (segment === 'step2') {
tpl = (<SecondStep url={url} />)
}
return tpl;
}
return (
<div className="section-form highlight">
<div className="container bg-white container-padding">
{/* other html code here */}
<div className="register-form text-center">
{ renderForm() }
</div>
</div>
</div>
);
}
子组件 - 第一步
import React from "react";
import { useDispatch } from 'react-redux'
import { useHistory } from "react-router-dom";
import { onStepChange } from '../../../redux/actions/registrationActions';
export default function FirstStep({
url
}) {
const dispatch = useDispatch()
const history = useHistory()
function nextStep(){
dispatch(onStepChange('step2', true));
history.push(`${url}/step2`)
}
return (
<div>
{/* other html code here */}
<a onClick={()=>nextStep()} className="boxed-btn3 btn-block">Next Step</a>
</div>
);
}
console.log(stepTracker) 在history.push() 被触发后变为undefined。
【问题讨论】:
-
你能建立一个最小的例子(也许在一个代码框里)并分享你的减速器逻辑吗?
-
@JosefWittmann 请检查这里的沙箱codesandbox.io/s/green-fog-n2bct。它在沙箱中有错误,但至少你可以看到设置。谢谢。
标签: reactjs react-redux state reducers