gpt4 book ai didi

reactjs - 为什么 react-router 在调度时自动返回到以前的路由

转载 作者:行者123 更新时间:2023-12-05 07:10:11 25 4
gpt4 key购买 nike

我有一个旧的应用程序想要添加 react-router 到它。具体来说,我正在使用 HashRouter。该应用程序还使用 reduxreact-redux,但没有其他中间件,如 saga 或 thunk。

该应用程序有多个选项卡,每个选项卡在挂载时都会调用 loadData 从后端获取数据。当我在选项卡#1 中并尝试导航到选项卡#2 时,调用了#2 的 loadData 方法。但是在调用 dispatch 时,页面会自动返回到选项卡#1。数据正在加载,加载完成后(已调用所有调度),我尝试导航到选项卡#2,这次成功了。

我不明白为什么。看起来每次调用 dispatch 时,路由器都会将窗口位置恢复到之前的位置。谁能给我一个解决方法的提示?

简化代码:

tab#1和tab#2结构相似

function tab1(props){
const [initialized, setInitialized] = useState(false);
const dispatch = useDispatch();

useEffect(()=>{
if(!initialized){
loadData();
setInitialized(true);
}
}, [initialized])

function loadData(){
// if data already in store, exit function early.
// otherwise:
dispatch({type: 'REQUEST_DATA'});
// fetch backend
// after receive json, dispatch
dispatch({type:'RECEIVE_DATA', data: json});
}

return (
// return
)

}

索引.js

import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore, combineReducers, applyMiddleware } from "redux";
import { HashRouter, Switch, Route } from "react-router-dom";
import logger from "redux-logger";
import * as reducers from "./reducers";
import createPersistedState from './createPersistedState';
...

let middlewares = [];
if (!window.production) {
middlewares = [logger]
}

const reducer = combineReducers({ ...reducers });

const persistedState = createPersistedState();

const store = createStore(reducer, persistedState, applyMiddleware(...middlewares));

...

const render = () => {
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<div id="root-container">
<HashRouter>
<ErrorBoundary >
<Header />
<div className="app-wrapper">
<Switch>
<Route path='/tab1' component={tab1}/>
<Route path='/tab2' component={tab2}/>
</Switch>
</div>
<Footer />
</ErrorBoundary>
</HashRouter>
</div>
</Provider>
</React.StrictMode>,
document.getElementById("app")
);
};

reducers/index.js

export {default as reducer1} from './reducer1'
export {default as reducer2} from './reducer2'
export {default as reducer3} from './reducer3'
export {default as reducer4} from './reducer4'

最佳答案

ok 结果不是 react-router 或 redux 的问题,而是我忽略更新的旧 reducer 。在那个 reducer 中,window.location.hash 默认被重置。这解释了一切——每次分派(dispatch)都会触发该 reducer 。删除后,一切都按预期工作。

关于reactjs - 为什么 react-router 在调度时自动返回到以前的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61331289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com