反应网址更改,但渲染不起作用?

时间:2019-12-26 17:37:38

标签: reactjs react-redux react-router redux-saga

我想在api之后重定向到页面,当我调度url更改但视图未呈现时,它在刷新页面时起作用。我如何从redux-saga重定向。

saga.js

export function* PQuotation({ payload }) {
 try {
const params = { PurchaseQuotation: payload.toJS() };

const res = yield call(request, `${BASE_URL}/purchase/quotations`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    ...authHeader(),
    module: `${modules.PurchaseQuotation}`,
  },
  body: JSON.stringify(params),
});

  yield put(purchaseQuotationCreateSuccess(res));
  yield put(push(`/some/page`));    //redirect to another page
} catch (err) {
  yield put(purchaseQuotationCreateError(err));
  }
}

app.js

render() {
return (
  <Fragment>
    <Helmet titleTemplate="%s ERP" defaultTitle="ERP">
      <meta name="description" content="ERP Application" />
    </Helmet>
     <BrowserRouter> 
    <Switch>
      <PrivateRoute
        exact
        path="/login"
        render={props => (
          <AuthLayout>
            <Login {...props} />
          </AuthLayout>
        )}
      />
      <PrivateRoute exact path="/logout" component={Logout} />
      <PrivateRoute exact path="/" component={HomePage} /> 
      <PrivateRoute exact path="/some/page" component={SomePage} />          
   </Switch>
    </BrowserRouter>
  </Fragment>
  );
  }

1 个答案:

答案 0 :(得分:0)

我建议遵循概念分离原则,其中React组件负责渲染,而Redux-Saga负责副作用。

所以方法应该是:

  1. 在传说中yield put(purchaseQuotationCreateSuccess(res));。我怀疑此操作将更新状态。设置一些变量,指示已成功创建采购报价。说isPurchaseQuoCreated: true
  2. 升级/包装路线<PrivateRoute />,以便将其连接到商店,并且如果成功创建了采购报价,它将进行重定向。

(下面的代码未经测试。用作提示)

const PurchaseQuotationRoute = ({isPurchaseQuoCreated, ...rest}) => (
    isPurchaseQuoCreated ? 
        <Redirect to='/some/page'/>
    :
        <PrivateRoute {...rest} />
)

export default connect(state => ({ isPurchaseQuoCreated: state.isPurchaseQuoCreated }))(PurchaseQuotationRoute) 

并在App.js

中使用
    <Switch>
      <PurchaseQuotationRoute
        exact
        path="/login"
        render={props => (
          <AuthLayout>
            <Login {...props} />
          </AuthLayout>
        )}
      />
      <PurchaseQuotationRoute exact path="/logout" component={Logout} />
      <PurchaseQuotationRoute exact path="/" component={HomePage} /> 
      <PrivateRoute exact path="/some/page" component={SomePage} />          
   </Switch>
    </BrowserRouter>

请注意,/some/page <PrivateRoute/>留在原处。如果我们已经在/some/page上,我们就不想重定向。