Перенаправить, когда результат функции true - PullRequest
0 голосов
/ 17 марта 2020

Я не могу перенаправить на другую страницу при успешном завершении процесса. Как я могу сделать это в рассылке .then? Я нашел способ без .then, создаю новое значение переменной по умолчанию как false, при запуске функции устанавливаю true. После того, как я контролировал, если правда Его работы {Blabla? : null}

  function save(control, e) {
if(control == true ){
dispatch(
  saveAction.save(
    control
  )
).then(e => {
    <Redirect to="/nextpage/"> //Don't work
}).catch(err => {
  console.log("Error");
});}}

кнопка

<button type="submit" onClick={(e) => save(item.control ,e)}> Next Page </button>

1 Ответ

0 голосов
/ 17 марта 2020

Не уверен, что это лучший способ сделать это, но это то, что я использовал раньше для asyn c Тип перенаправления:

const myAsyncComponent = () => {
  const [redirect, setRedirect] = useState(false);

  // Here's your original code
  function save(control, e) {
    if (control == true ) {
      dispatch(
        saveAction.save(
          control
        )
      ).then(e => {
          // <Redirect to="/nextpage/"> //Don't work
          setRedirect(true); // should work:
      }).catch(err => {
        console.log("Error");
      });
    }
  }

  // ... any of your other stuff

  // Right before you return your usual component jsx, put this in before that:
  if (redirect) {
    return <Redirect to="/nextpage" />;
  }

  // This code won't be reached if `redirect` is true,
  // instead it will return the Redirect. But when `redirect` is false,
  // this will be returned:
  return (
    <button
      type="submit"
      onClick={(e) => save(item.control ,e)}
    >
      Next Page
    </button>
  );
};
...