简体   繁体   English

如何在 function 调用/手动中调用反应路由器 DOM 链接

[英]How to call react router DOM link inside a function call/manually

The high level task I would like to do is to call a Link from react-router-dom inside a function call.我想做的高级任务是在 function 调用中从 react-router-dom 调用一个链接。

My use case: I have a submit button which once clicked calls a POST API.我的用例:我有一个提交按钮,点击后会调用 POST API。 I want to check the response of the POST API and if it is successful call it will go to my Link to my successful submission page.我想检查 POST API 的响应,如果它成功调用,它将 go 到我的链接到我的成功提交页面。 If it is an error I would like to call the Link to my error page.如果这是一个错误,我想调用我的错误页面的链接。 One factor to consider is that the POST API takes about 2 seconds to respond.要考虑的一个因素是 POST API 需要大约 2 秒的响应时间。

Ideally I would like the Link component to not be directly on the submit button component.理想情况下,我希望 Link 组件不要直接位于提交按钮组件上。 I would like to call a function once the button is clicked which contains the Link component after my API responds.在我的 API 响应后,单击包含链接组件的按钮后,我想调用 function。

Here is my current code:这是我当前的代码:

    function SubmitFcn(){

const submitPostAPI = (async () => {await axios({
//data passed 
})
      .then(function (response) {
//here is where I capture the API response
 })
      .catch(function (error) {});
  });

return (
    <div>
      <Link to="/SubmitPage" style={{ textDecoration: "none" }}>
        <Button
           disabled={btnDisabled}
          id="submitButtonFormPOST"
          variant="contained"
          color="primary"
          onClick={submitPostAPI}
          data-testid="submitButtonelement"
        >
          {" "}
          Submit
        </Button>
      </Link>
    </div>
  );
}
}

 

Here is what I would like my code to resemble, the problem is it is not compiling because I am calling the Link component incorrectly.这是我希望我的代码类似的内容,问题是它没有编译,因为我错误地调用了 Link 组件。

  function SubmitFcn(){

const submitPostAPI = (async () => {await axios({
//data passed 
})
      .then(function (response) {
//here is where I capture the API response
LinkFunction(response.status)
 })
      .catch(function (error) {});
  });

return (
    <div>
      <Link to="/SubmitPage" style={{ textDecoration: "none" }}>
        <Button
           disabled={btnDisabled}
          id="submitButtonFormPOST"
          variant="contained"
          color="primary"
          onClick={submitPostAPI}
          data-testid="submitButtonelement"
        >
          {" "}
          Submit
        </Button>
      </Link>
    </div>
  );
}
}

function LinkStatus(result){
if(result === 201){
<Link to="/Submitsucess"/>}

else{
<Link to="/ErrorPage:/>
}
}

Use history.push("/submitSuccess") or history.push("/errorPage") via the history object provided from route props or useHistory react hook.通过route propsuseHistory react hook 提供的history object 使用history.push("/submitSuccess")history.push("/errorPage")

You likely may also want to remove the Link wrapping the button as that can interfere with this component remaining mounted.您可能还希望删除包裹按钮的Link ,因为这可能会干扰组件保持安装状态。

If the component is directly rendered by a Route component then it receives the route props, so just access history from the props object如果组件直接由Route组件渲染,那么它会接收路由 props,因此只需从 props object 访问history

props.history

otherwise use the useHistory react hook否则使用useHistory反应钩子

const history = useHistory();

So component could look similar to either of these所以组件可能看起来类似于其中任何一个

const MyComponent = ({ history }) => {
  const submitPostAPI = async () => {
    await axios({
      //data passed
    })
      .then(function (response) {
        linkStatus(response.status);
      })
      .catch(function (error) {
        history.push("/errorPage"); // <-- go to error page here as well
      });
  };

  function linkStatus(result) {
    if (result === 201) {
      history.push("/submitSuccess");
    } else {
      history.push("/errorPage");
    }
  }

  return (
    <div>
      <Button
        disabled={btnDisabled}
        id="submitButtonFormPOST"
        variant="contained"
        color="primary"
        onClick={submitPostAPI}
        data-testid="submitButtonelement"
        type="button"
      >
        Submit
      </Button>
    </div>
  );
};

or或者

const MyComponent = ( ) => {
  const history = useHistory();

  const submitPostAPI = async () => {
    await axios({
      //data passed
    })
      .then(function (response) {
        linkStatus(response.status);
      })
      .catch(function (error) {
        history.push("/errorPage"); // <-- go to error page here as well
      });
  };

  function linkStatus(result) {
    if (result === 201) {
      history.push("/submitSuccess");
    } else {
      history.push("/errorPage");
    }
  }

  return (
    <div>
      <Button
        disabled={btnDisabled}
        id="submitButtonFormPOST"
        variant="contained"
        color="primary"
        onClick={submitPostAPI}
        data-testid="submitButtonelement"
        type="button"
      >
        Submit
      </Button>
    </div>
  );
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在React Router内的任何路由上调用函数? - how to call function on any route inside react router? react-router-dom: 无效的钩子调用,只能在 function 组件的主体内部调用钩子 - react-router-dom: Invalid hook call, Hooks can only be called inside of the body of a function component 如何访问a内的href<link> 在 react-router-dom 中标记? - How to access a href inside a <Link> tag in react-router-dom? 使用 React-Router-Dom,有没有办法在事件/函数调用上重定向页面而不是使用<link ...>并且需要按下按钮? - Using React-Router-Dom, is there a way to re-direct a page on an event/function call rather than of using <Link ... /> and needing to press a button? 添加 React Router DOM 时出错:无效的钩子调用。 钩子只能在 function 组件的主体内部调用 - Error While adding React Router DOM: Invalid hook call. Hooks can only be called inside of the body of a function component React-router:如何手动调用 Link? - React-router: How to manually invoke Link? React &amp; React Router,无法调用父函数 - React & React Router, Unable to call the parent function 重定向(反应路由器dom),给出了期望的赋值或函数调用,而是看到了一个表达式no-unused-expressions - Redirect (react router dom) giving Expected an assignment or function call and instead saw an expression no-unused-expressions 如何在React / Jsx中的渲染器内部调用函数 - How to Call a Function inside a Render in React/Jsx 如何在 React function 组件中调用 API? - How to call API inside React function component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM