redux订阅触发,但存储对象为空

时间:2019-07-24 09:44:38

标签: redux subscribe

此问题与在redux中的subscribe方法中链接状态和存储有关。 请注意,我在stackoverflow中找到了许多与redux反应有关的答案,但这与纯redux有关。

代码中的问题是,订阅方法存储对象内部不可用。但是调度工作和内部调度可以看到商店也在更新。

如何在订阅方法中存储内容。

这是我在名为redrec.js的文件中的代码

const {createStore} = require("redux");
const initialState = { age:21 };
const myReducer = (state = initialState, action) =>
{
    if(action.type === 'ADD'){ state.age += 1;  }

    // console.log('Hello' );
    // console.log(JSON.stringify(state) );
    // console.log(state.age);

    return  state;
}
const store = createStore(myReducer);
store.dispatch({type: 'ADD'});
store.subscribe(()=>{

    console.log('Hello' );
    console.log(JSON.stringify(store) );
    console.log(store.age);

});
store.dispatch({type: 'ADD'});

我用命令执行它

node redrec.js

我得到以下结果

Hello
{}
undefined

如果我不评论注释的代码,则会看到此结果。

Hello
{"age":21}
21
Hello
{"age":22}
22
Hello
{"age":23}
23
Hello
{}
undefined

那么,如何获取状态对象库?

2 个答案:

答案 0 :(得分:0)

得到答案。 从存储中,我们需要使用getState方法获取状态。 因此在内部订阅方法中,

更改以下内容

    console.log(JSON.stringify(store.getState()) );
    console.log(store.getState().age);

更新正确的代码是

const {createStore} = require("redux");
const initialState = { age:21 };
const myReducer = (state = initialState, action) =>
{
    if(action.type === 'ADD'){ state.age += 1;  }

    // console.log('Hello' );
    // console.log(JSON.stringify(state) );
    // console.log(state.age);

    return  state;
}
const store = createStore(myReducer);
store.dispatch({type: 'ADD'});
store.subscribe(()=>{

    console.log('Hello' );
    console.log(JSON.stringify(store.getState()) );
    console.log(store.getState().age);

});
store.dispatch({type: 'ADD'});

答案 1 :(得分:0)

正如redux文档中所说,redux状态是不可变的。

我可以在减速器中看到您正在对其进行变异并返回变异值。相反,您需要创建一个新对象并将其返回。

return {
    ...state,
    age: state.age +=1,
};

这是因为在组件中将状态映射到prop时,仅当prop的引用更改时才会呈现。

相关问题