简体   繁体   English

如何将 state 值分派给 Redux-toolkit 中的常量变量?

[英]How to I dispatch a state value to an const variable in Redux-toolkit?

I am trying get an error to show in my component which is being dispatched from my actions and assigned to my errorAlert constent, however it always comes back as null even when there is content in my state as per console.log .我正在尝试在我的组件中显示一个错误,该错误是从我的操作中分派并分配给我的errorAlert常量的,但是它总是以 null 的形式返回,即使我的 state 中有内容console.log I have shared the console log results below.我在下面分享了控制台日志结果。

Is there an issue when assigning a redux state variable to a const?将 redux state 变量分配给 const 时是否存在问题?

slice.js切片.js

const auth = createSlice({
    name: "auth",
    initialState: verifiedResult: {},
    reducers: {
        verifySuccess(state, { payload }) {
            state.verifiedResult = payload;
            state.isLoading = false;
            state.error = null;
        }
    }

action.js动作.js

...
if (result.state === "pending") {
    await new Promise((resolve) => setTimeout(resolve, 10000));
       } else if (result.state === "failed") {
            dispatch(verifySuccess(result));
    break;

component.js组件.js

....
const errorAlert =
        auth.verifiedResult.cel_number === false
            ? "The number associated with your account is not a valid."
            : auth.verifiedResult.prepaid_number === false
            ? "Mobile number is not Prepaid or is not active."
            : auth.verifiedResult.has_recharged === false
            ? "Mobile number must be recharged in the past 30 days"
            : null;
return (
<>
{errorAlert && <div>{errorAlert}</div>}
</>
)}

console.log控制台日志

::auth.verifiedResult::
{
state: "failed"
cel_number: 'XXX XXX XXX'
prepaid_number: false
recharged: false
}

:::errorAlert::: null

在此处输入图像描述

It shows Mobile number is not Prepaid or is not active.它显示Mobile number is not Prepaid or is not active. in my case.就我而言。 Make sure your auth.verifiedResult is correctly written(you don't use comma after every object property).确保您的auth.verifiedResult书写正确(您不要在每个 object 属性后使用逗号)。

 const auth = {}; auth.verifiedResult = { state: 'failed', cel_number: 'XXX XXX XXX', prepaid_number: false, recharged: false, }; const errorAlert = auth.verifiedResult.cel_number === false? 'The number associated with your account is not a valid.': auth.verifiedResult.prepaid_number === false? 'Mobile number is not Prepaid or is not active.': auth.verifiedResult.has_recharged === false? 'Mobile number must be recharged in the past 30 days': null; console.log(errorAlert); // Mobile number is not Prepaid or is not active.

Did you mean你的意思是

if (result.state === "pending") ? if (result.state === "pending")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM