【问题标题】:Reducer state lost after history.push()在 history.push() 后减速器状态丢失
【发布时间】: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


【解决方案1】:

问题出在你的 reducer 逻辑中(仅在沙箱中可见,问题中没有)。

问题就在那里:

return {
  ...state.stepTracker,
  [fieldName]: value
};

这是它的工作原理:

return {
  ...state,
  stepTracker: {
    ...state.stepTracker,
    [fieldName]: value
  }
}

原因是,stepTracker 属性在你的 reducer 状态下被替换了。所以最初 reducer 的状态是这样的

{
  stepTracker: {
    step1: true,
    step2: false,
    step3: false
  }
}

但是变成了这个:

{
  step1: true,
  step2: false,
  step3: false
}

【讨论】:

  • 我明白了。会先试一试。谢谢! :)
猜你喜欢
  • 2023-01-13
  • 2021-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-27
  • 2016-04-23
  • 2018-05-13
相关资源
最近更新 更多