【问题标题】:React/Redux get the state from another component using storeReact/Redux 使用 store 从另一个组件获取状态
【发布时间】:2018-07-25 20:28:59
【问题描述】:

我刚开始使用 Redux,因为我的应用程序由于将状态传递给不同的组件而变得复杂。我在尝试将数据检索到其他组件时遇到错误。

我想将状态传递给另一个组件,但我得到了这个错误:

store.js

import {createStore} from 'redux';

const initialState = {
  regionId: 0
};
const reducer = (state = initialState, action) => {

  if(action.type === "REGIONAL_ID") {
     return {
        regionId: action.regionId
      };
    }
    return state;
}
const store = createStore(reducer);
store.subscribe(() => {
  console.log(store.getState().regionId)
})

export default store;

在我的 Network.js 组件中,我正在调用它

const REGION_ID = store.subscribe(() => {
    return store.getState().regionId;
})
console.log(REGION_ID);

我尝试了以下方法,但这也给了我一个错误。非常感谢!

const REGION_ID = return store.getState().regionId;

【问题讨论】:

    标签: javascript reactjs react-native redux react-redux


    【解决方案1】:

    这不是错误。 store.subscribe() 方法返回一个unsubscribe 方法,console.log() 显示该方法的实现:

    const REGION_ID = store.subscribe(() => {
        return store.getState().regionId; // this is isn't returned to REGION_ID
    })
    console.log(REGION_ID); // REGION_ID contains the unsubscribe method
    

    如果您想使用从状态中获得的regiondId,请将您的代码放在订阅回调中:

    tore.subscribe(() => {
        const REGION_ID = store.getState().regionId;
        console.log(REGION_ID );
    })
    

    const REGION_ID = return store.getState().regionId; 这一行会产生错误,因为you can't return outside of a function

    【讨论】:

    • 哦,我明白了。谢谢!
    • 如果您不介意...我如何在订阅函数之外访问REGION_ID 变量?这就是我尝试返回方法的原因,但不确定如何在外面获取更新的值。
    • 有一种简单的方法将REGION_ID 更改为let 而不是const,然后在订阅中分配值,但是......你怎么知道订阅发生了,并且外部 REGION_ID 变量是否已更新?为什么不在订阅回调中运行需要 REGION_ID 的代码?
    • 我尝试了以下let Updated = store.subscribe(() => { let REGION_ID = store.getState(); }),但返回了取消订阅方法。我的主要问题是试图在export default new NetworkService(); 中获取服务组件的状态,但this.props 返回未定义,所以我尝试订阅,但我也遇到了问题。
    • let REGION_ID; store.subscribe(() => { REGION_ID = store.getState(); }); - 您可以在订阅之外访问REGION_ID,但您不知道它何时准备好/更新。您应该使用完整的用例打开另一个问题。我认为您的解决方案是错误的。
    猜你喜欢
    • 2021-02-05
    • 2019-08-10
    • 1970-01-01
    • 2019-07-30
    • 2019-04-27
    • 2017-04-02
    • 2019-05-17
    • 2018-11-16
    • 2018-09-12
    相关资源
    最近更新 更多