反应还原。如何在第一个应用程序渲染时获取更新的存储状态
React-redux. How to get updated store state on first application render
我很好奇渲染组件的最佳做法是什么,以及如何重新渲染它以获得更新的商店。
例如,在当前时刻,项目有一个 store 监听 react-router 并存储当前位置。
店铺
export default (initialState = {slidesData}) => {
const store = createStore(
makeRootReducer(),
initialState
)
store.asyncReducers = {}
store.unsubscribeHistory = hashHistory.listen(updateLocation(store));
if (module.hot) {
module.hot.accept('./reducers', () => {
const reducers = require('./reducers').default
store.dispatch(reducers(store.asyncReducers))
})
}
return store
}
位置缩减器
export const LOCATION_CHANGE = 'LOCATION_CHANGE';
const hash = '/#/',
browser = '/';
// Action
export function locationChange (location = hash) {
return {
type: LOCATION_CHANGE,
payload: location
}
}
// Action creator
export const updateLocation = ({ dispatch }) => {
return (nextLocation) => dispatch(locationChange(nextLocation))
}
// Reducer
const initialState = null;
export default function locationReducer (state = initialState, action) {
return action.type === LOCATION_CHANGE
? action.payload
: state
}
因此,在第一次加载应用程序时,订阅存储的组件会收到 initialState = null
,当第一次路由更改发生时,存储更新和组件现在会收到 "/current-route"
。
能否请您分享您的想法,以便在订阅它的组件收到 null
之前获得 "current-route"
。
或者如果组件收到 null
并触发它们的重新渲染以显示更新的商店,如何处理组件渲染?
我知道在派发任何操作(如路由更改或其他)之前将某些内容放入状态的唯一方法是将其放入减速器的默认状态对象中。
即const reducer = (state = <default state object>, action) => {...
所以在你的情况下,我建议不要使用 null
初始化,而是从 window
对象中获取当前路由:
// Reducer
const initialState = window.location.pathname;
我很好奇渲染组件的最佳做法是什么,以及如何重新渲染它以获得更新的商店。
例如,在当前时刻,项目有一个 store 监听 react-router 并存储当前位置。
店铺
export default (initialState = {slidesData}) => {
const store = createStore(
makeRootReducer(),
initialState
)
store.asyncReducers = {}
store.unsubscribeHistory = hashHistory.listen(updateLocation(store));
if (module.hot) {
module.hot.accept('./reducers', () => {
const reducers = require('./reducers').default
store.dispatch(reducers(store.asyncReducers))
})
}
return store
}
位置缩减器
export const LOCATION_CHANGE = 'LOCATION_CHANGE';
const hash = '/#/',
browser = '/';
// Action
export function locationChange (location = hash) {
return {
type: LOCATION_CHANGE,
payload: location
}
}
// Action creator
export const updateLocation = ({ dispatch }) => {
return (nextLocation) => dispatch(locationChange(nextLocation))
}
// Reducer
const initialState = null;
export default function locationReducer (state = initialState, action) {
return action.type === LOCATION_CHANGE
? action.payload
: state
}
因此,在第一次加载应用程序时,订阅存储的组件会收到 initialState = null
,当第一次路由更改发生时,存储更新和组件现在会收到 "/current-route"
。
能否请您分享您的想法,以便在订阅它的组件收到 null
之前获得 "current-route"
。
或者如果组件收到 null
并触发它们的重新渲染以显示更新的商店,如何处理组件渲染?
我知道在派发任何操作(如路由更改或其他)之前将某些内容放入状态的唯一方法是将其放入减速器的默认状态对象中。
即const reducer = (state = <default state object>, action) => {...
所以在你的情况下,我建议不要使用 null
初始化,而是从 window
对象中获取当前路由:
// Reducer
const initialState = window.location.pathname;