【发布时间】: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