【问题标题】:Why can't my selector read `state`? state is not defined为什么我的选择器无法读取“状态”?状态未定义
【发布时间】:2019-08-06 00:36:54
【问题描述】:

我正在完成一个非常简单的 Redux 应用程序,它会获取存储在 Redux 存储中的报价并将其呈现在屏幕上。努力让选择器读取状态(无法读取未定义的属性quoteText

尝试移动状态的定义(const state = store.getState(); ) 周围(想知道这是否与 JS 执行顺序有关但没有成功)


const getRandomQuote = () => {
const quotes = [
    {
        quoteText:"XXXXXX",
        quoteAuthor:"YYYY",
    },
    {
        quoteText:"AAAA",
        quoteAuthor:"BBBB",
    }
];
  return quotes[Math.floor(Math.random() * quotes.length)];
};

const defaultQuote = getRandomQuote();

const NEW_QUOTE = 'NEW_QUOTE';

const newQuoteActionCreator = () => {
  let quoteObject = getRandomQuote();
  return {
    type: NEW_QUOTE,
    payload: quoteObject
  };
};

const getNextQuoteReducer = (state = defaultQuote, action) => {
  switch (action.type) {
    case NEW_QUOTE:
       return {
         ...state,
         data: action.payload
       };
    default:
       return state;
  }
};

const store = Redux.createStore(getNextQuoteReducer);
const state = store.getState();

const newQuoteButton = document.getElementById('new-quote');
const quoteTextContent = document.getElementById('text');

store.subscribe((state) => {
  quoteTextContent.innerHTML = state.data.quoteText;
});

newQuoteButton.addEventListener('click', () => {store.dispatch(newQuoteActionCreator());
});

document.addEventListener('DOMContentLoaded', () => {
  quoteTextContent.innerHTML = state.quoteText;
});

希望能够将存储侦听器 (store.subscribe) 定义为 Redux 选择器函数(接收 state 作为参数或能够读取全局状态变量),但没有运气。我总是收到指向 state 未定义的错误。

欢迎指点。

【问题讨论】:

  • 存储监听器不获取状态,他们需要从存储中获取状态。 redux.js.org/api/store#subscribelistener 你说你做到了,但实际上没有看到不起作用的代码,谁知道你实际上在做什么。你当前拥有的state将获得那个时间点的状态。
  • @DaveNewton - 我认为你可以继续发布它作为答案(与store.subscribe 期望的小sn-p)
  • @vivalldi 所以...很多...努力...

标签: javascript redux state


【解决方案1】:

不,store.subscribe() 确实将当前状态作为参数传递给订阅者(请参阅API docs for store.subscribe for details)。因此,您不能将选择器函数用作订阅者回调。 (此外,由于定义上的选择器只是“选择”并返回一个值,但不对其做任何其他事情,因此使用选择器作为订阅者回调无论如何都是没有意义的。)

相反,订阅者回调必须在回调内调用store.getState() 以检索最新状态。然后您可以调用someSelector(state) 来检索您关心的值。

请参阅我的帖子The History and Implementation of React-Redux 以进一步解释 React-Redux 等 Redux UI 层如何处理订阅和状态提取方面。

【讨论】:

  • 谢谢。很棒的帖子!
猜你喜欢
  • 2017-04-07
  • 2019-06-08
  • 1970-01-01
  • 2021-11-28
  • 2019-07-25
  • 2020-11-05
  • 2021-07-07
相关资源
最近更新 更多