Как запустить вторую функцию после запуска функции в функциональном компоненте (React, React Hooks) - PullRequest
0 голосов
/ 13 июля 2020

Итак, у меня есть кнопка:

<button onClick={doSomething}>Do it</button>

И у меня есть функция

const doSomething = () => {
  console.log(1)
}

И я хочу, чтобы console.log(2) срабатывал после запуска doSomething.

Примерно так:

const doSomething = () => {
  console.log(1)
  console.log(2)
}

А вот этот console.log(2) сразу срабатывает. Я хочу, чтобы при нажатии на кнопку запускалось console.log(2) после console.log(1).

Нужно ли мне здесь использовать useEffect()? Если да, то как?

РЕДАКТИРОВАТЬ :

Вот в чем проблема. getQuestions() срабатывает сразу после выполнения функции a. Я хочу, чтобы getQuestions() срабатывал после завершения props.answerQuestion().

   const a = (e) => {
        e.preventDefault();

        props.answerQuestion({
            question: question,
            answer: answer,
        });

        getQuestions();
    };

EDIT2:

export const answerQuestion = (answerQuestion) => (dispatch) => {
    const token = localStorage.getItem("token");
    if (token) {
        axios
            .post("http://localhost:5000/answerQuestion", answerQuestion, {
                headers: {
                    "X-Auth-Token": token,
                },
            })
            .then((res) => {
                dispatch({
                    type: ANSWER_QUESTION,
                    payload: res.data,
                });
            });
    }
};

Ответы [ 2 ]

1 голос
/ 13 июля 2020

Можно JavaScript Promises для этой задачи. Использование Promises в answerQuestion() Функция позволит вам связать методы .then() и .catch() в a function

export const answerQuestion = (answerQuestion) => (dispatch) => return new Promise((resolve, reject) => {
    const token = localStorage.getItem("token");
    if (token) {
        axios
            .post("http://localhost:5000/answerQuestion", answerQuestion, {
                headers: {
                    "X-Auth-Token": token,
                },
            })
            .then((res) => {
                dispatch({
                    type: ANSWER_QUESTION,
                    payload: res.data,
                });
                resolve();
            })
            .catch((error) => {
                reject(error);
             })
    }
});
const a = (e) => {
        e.preventDefault();

        props.answerQuestion({
            question: question,
            answer: answer,
        })
        .then(() => {
            getQuestions();
         })
         .catch((error) => {
            console.log(error)
          })

        
    };

1 голос
/ 13 июля 2020

Вам не нужно использовать useEffect в этом сценарии, все, что вам нужно сделать, это дождаться разрешения вызова api перед вызовом getQuestions. один из способов: sh это:

// update answerQuestion into an async function
export const answerQuestion = async (answerQuestion) => async (dispatch) => {
    const token = localStorage.getItem("token");
    if (token) {
        const response = await axios // <--- add await here
            .post("http://localhost:5000/answerQuestion", answerQuestion, {
                headers: {
                    "X-Auth-Token": token,
                },
            })
        await dispatch({
            type: ANSWER_QUESTION,
            payload: response.data,
        });
    }
};

затем в вашем компоненте:

   const a = async (e) => {
        e.preventDefault();

        await props.answerQuestion({
            question: question,
            answer: answer,
        });

        getQuestions();
    };
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...