我有一个带有以下代码的非 React 项目
.
_index.js_
import configureStore from 'js/store/configureStore'
/* Redux Imports */
import { createPage } from 'js/actions/page'
// Boot the App
document.addEventListener('DOMContentLoaded', function () {
const initialState = window.__INITIAL_STATE__
const pageId = window.__INITIAL_STATE__.page
const store = configureStore(initialState)
store.dispatch(createPage(pageId))
})
*actions/page.js*
function initPage (pageId) {
return {
type: 'CREATE_PAGE',
page: pageId
}
}
export function createPage (pageId) {
return dispatch => {
dispatch(initPage(pageId))
}
}
_reducers/page.js_
/**
* Page Mediators get imported here
* Page Mediators are brokers that hold page initialization.
* The bundle includes all page mediators but they will not be activated
* unless thre reducer calls them.
*/
import * as cart from 'js/templates/cart'
/**
* This is a edge case, index.js boots the app and we are subscribing to
* a Redux @<strong i="11">@INIT</strong> action instead of adding one more layer of actions
* which leads to unintended scenarios.
*/
const page = (state = {page: []} , action) => {
console.log(state)
switch (action.type) {
case '@<strong i="12">@INIT</strong>':
console.log('initializing page:' + state.id)
console.log(state)
dispatch({type: 'CREATE_PAGE',page: state.id})
cart.init()
return state
case 'CREATE_PAGE':
console.log('initializing page:' + state.id)
cart.init()
return state
default:
return state
}
}
export default page
我遇到的问题是actions/page.js
永远不会看到CREATE_PAGE
操作。 有什么想法吗?
无关但
- 这是一个边缘情况,index.js 启动应用程序,我们正在订阅
- 一个 Redux @@ INIT动作,而不是再添加一层动作
- 这会导致意想不到的情况。
可以在任何一天破坏您的应用程序。
我们特别说:
- 这些是 Redux 保留的私有操作类型。
- 对于任何未知操作,您必须返回当前状态。
- 如果当前状态未定义,则必须返回初始状态。
- 不要在代码中直接引用这些操作类型。
谢谢@gaearon - 我打算删除它,我添加它是因为我创建的操作从未见过 - 我做错了什么?
请使用 StackOverflow 解决问题。 我们尝试将问题跟踪器用于错误和功能讨论,但不用于支持。
至于代码,它通过执行副作用( cart.init()
)并尝试在 reducer 内分派动作( dispatch()
)违反了 Redux 的约束。 这是不允许的,正如文档中不止一次指出的那样。 Reducers 必须是纯函数,所以你应该在分发 action 之前或之后放置副作用。
如果您在减速器内调度,您的代码应该会失败。 如果它没有失败,也许你有一个 Promise 在某处吞下错误。 从这段代码中很难说更多。
最有用的评论
无关但
可以在任何一天破坏您的应用程序。
我们特别说: