簡體   English   中英

當我使用 history.push() 我的組件不呈現時,我需要刷新頁面

[英]When I use history.push() my component don't render, I need to refresh the page

我正在使用 react-router-dom 來制作我的路線。

我有一個名為AppRouter.js的文件,其中包含我的路由:

const AppRouter = props => {

    const loading = useSelector(state => state.loadingStates)
    return (
        <Router>
            <Switch>
                <div>
                    <Route exact path="/">
                        <Redirect
                            to={{
                                pathname: "/login",
                            }}
                        />
                    </Route>
                    <Route path="/home" component={Home} />
                    <Route path="/registrar" component={LoginWrapper} />
                    <Route path="/login" component={LoginWrapper} />
                </div>
            </Switch>
        </Router>
    );
}

export default AppRouter

我的 index.js 呈現這個文件路由器:

ReactDOM.render(
    <Provider store={store}>
            <AppRouter/>
    </Provider>, document.getElementById('root'));

因此,當我轉到localhost:3333我被登錄頁面重定向。 在登錄頁面中,用戶登錄后,我執行history.push('/home')

function* makeLogin(action) {
    yield put(allActions.loadingActions.startLoading());
    try {    
        const { data } = yield call(api.post, '/login', action.payload);
        yield put(allActions.loginActions.setUser(data))
        yield put(allActions.loadingActions.endLoading());
        localStorage.setItem('currentUser', JSON.stringify(data))
        history.push('/home')
    } catch (e) {
        console.log(e)
    }
}

我的瀏覽器中的鏈接更新為localhost:3333/home但我的組件仍然顯示登錄頁面,我需要重新加載到組件渲染。

我的history.js由發出 makeLogin 請求的文件 saga.js 導入:

import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

export default history;

為什么會發生這種情況? 我如何解決這個問題?

您需要將自定義歷史記錄傳遞給路由器

**** see change ****
import history from "../path to your history.js file";

const AppRouter = props => {

const loading = useSelector(state => state.loadingStates)
return (

    **** see change ****
    <Router history={history }>
        <Switch>
            <div>
                <Route exact path="/">
                    <Redirect
                        to={{
                            pathname: "/login",
                        }}
                    />
                </Route>
                <Route path="/home" component={Home} />
                <Route path="/registrar" component={LoginWrapper} />
                <Route path="/login" component={LoginWrapper} />
            </div>
        </Switch>
    </Router>
);
}

export default AppRouter

請參閱此頁面以供參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM