Pra*_*tha 5 javascript reactjs redux
我想提取 subreddits 并以列表形式向用户显示。当用户从选项菜单中更改 subreddit 时,我会将状态推送到浏览器历史记录。
现场演示: https: //react-7qfrxx.stackblitz.io
再生产:
frontend。列出后reactjs再次选择。实时编辑器:https://stackblitz.com/edit/react-7qfrxx
在AsyncApp.js 中Line 36:
this.props.dispatch(push('/' + nextSubreddit))
Run Code Online (Sandbox Code Playgroud)
当按下后退/前进时,如何向用户显示上一个或下一个缓存/状态?有人可以编辑我的在线应用程序以向我展示正确的方法吗?我两天以来一直在尝试解决这个问题,但没有成功。
我需要在不刷新页面的情况下执行此操作。(异步)
以前的解决方案不起作用,所以这是我更新的答案:我认为最好的选择是侦听 的LOCATION_CHANGE操作类型connected-react-router并在那里分派您 selectSubreddit 。使用LOCATION_CHANGE在项目中没有记录connected-react-router,但是旧项目react-router-redux的文档确实提到了它。
我们实际上可以创建一个中间件函数来完成此任务:
import { LOCATION_CHANGE } from 'connected-react-router'
import { selectSubreddit } from './actions';
export const listenRouteMiddleware = ({ dispatch, getState }) => (next) => (action) => {
if (action.type === LOCATION_CHANGE) {
const { pathname } = action.payload.location;
if (pathname !== '/') {
const pathArray = pathname.split('/');
const selectSub = pathArray[pathArray.length - 1];
next(action); // before dispatch, otherwise history breaks
dispatch(selectSubreddit(selectSub));
return;
}
}
next(action);
}
Run Code Online (Sandbox Code Playgroud)
接下来,将其添加到您的其他中间件中:
import thunkMiddleware from 'redux-thunk'
import { createBrowserHistory } from 'history'
import { applyMiddleware, compose, createStore } from 'redux'
import { routerMiddleware } from 'connected-react-router'
import createRootReducer from './reducers'
import { listenRouteMiddleware } from './middleware';
export const history = createBrowserHistory()
export default function configureStore(preloadedState) {
const store = createStore(
createRootReducer(history), // root reducer with router state
preloadedState,
compose(
applyMiddleware(
listenRouteMiddleware,
routerMiddleware(history), // for dispatching history actions
thunkMiddleware
// ... other middlewares ...
),
),
)
return store
}
Run Code Online (Sandbox Code Playgroud)
更改更改处理程序以仅在选择选项时推送新 URL:
handleChange(nextSubreddit) {
this.props.dispatch(push('/' + nextSubreddit))
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1856 次 |
| 最近记录: |