【问题标题】:Where to make api call everytime a modal opens in reactjs每次在 reactjs 中打开模式时在哪里进行 api 调用
【发布时间】:2019-12-01 05:28:07
【问题描述】:

我有一个模式,应该在单击按钮时打开。 基于按钮点击,它触发一个带有 id 的打开动作,这个 id 被添加到状态中。

但问题是我无法在模式渲染之前(当模式打开时)从状态访问这个 id。

事件流程是这样的:

按钮单击 --> 使用 id 调度 openmodal 操作 --> active prop 变为 true --> modal 打开。

但在模态渲染之前我无法访问 id。

【问题讨论】:

  • 你能创建和分享你的代码沙盒吗
  • @reactdoubt 发布您的代码您尝试了什么?
  • openmodal 调度可以在中间件的帮助下处理 api 请求,当您的 modal 打开时,它会显示微调器,直到您的原始组件带来 api 请求的响应。由于它是模态的,因此您的原始组件将永远不会卸载,因此您可以在那里处理它。不要忘记在关闭模式时调用 componentWillUnmount。

标签: javascript reactjs redux react-redux


【解决方案1】:

您可以为此使用redux-thunk 或类似的库。在 redux-thunk 操作中,您可以访问当前状态,还可以调度操作。

const myAction = () => (dispatch, getState) => {

  // get state here and dispatch actions with it
  const id = getState().modalId;

  dispatch({
    type: 'ANOTHER_ACTION',
    modalId
  });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 2011-07-17
    • 1970-01-01
    相关资源
    最近更新 更多