首页 > 解决方案 > 在 componentDidMount 或单击按钮时调用 API

问题描述

我是新来的react-redux。在这里,我有一个按钮,就像

<button className="btn btn-primary fetchBtnSize"
            disabled={this.state.disableFetchQuestion}
            onClick={() => this.fetchQuestions()}>
            Fetch Questions
                </button>
        </div >

现在,在这种方法中

fetchQuestions() {   this.props.fetchQuestions(result); }

现在在我的行动中,

export function fetchQuestions(arrayOfQuesObjs) {
    return (dispatch) => {
        dispatch({
            type: REQUEST_INITIATED
        });
        post(FETCH_QUESTIONS_URL, arrayOfQuesObjs)
            .then((response) => {
                if (response.status === 200) {
                    dispatch({
                        type: REQUEST_SUCCESSED,
                    });
                    history.push('/quiz-questions');
                    dispatch({
                        type: FETCHING_QUESTIONS_SUCCESS,
                        data: response.payload,
                    })
                }
                else {
                    dispatch({
                        type: REQUEST_SUCCESSED
                    });
                    toastr.error(response.status.message);
                    dispatch({
                        type: FAILED_QUESTIONS_FETCHING,
                        data: response.status,
                    });
                    if (response.status === 401) {
                        toastr.error("Please login again");
                        localStorage.clear();
                        history.push('/');
                    }
                }
            })
    }
}

所以,只有在成功之后,我才会将用户重定向到quiz-questions page.

现在,我正在渲染一个组件。

现在,发生的情况是,当用户单击当时的重新加载页面时,quiz-questions从服务器获取的这些数据会丢失。因为状态被清除了。现在,我所做的是,

on history.push({ pathName: '/quiz-questions', state : { data: 1, isfetch: true   }})

所以,当我点击重新加载按钮时,我将从props.location.state.data

接着

componentDidMount() { this.props.fetchQuestions(props.location.state.data);  }

现在,在这里,发生了什么,单击button如果我删除 api 调用并将用户重定向到/quiz-questions那个时间,如果 api 失败,那么用户应该在previous page only

所以,我不明白在哪里调用它API。如果我在这两个地方都保留它it will call two times。那么,我该如何解决这个问题?

标签: javascriptreactjsreduxreact-redux

解决方案


在任何情况下,redux 存储中的数据在重新加载后都不会保留。您需要从逻辑上处理这种情况。看看这个教程。您应该以这种方式管理数据流。

简而言之,即使在重新加载之后,您在多个路由上需要的任何数据都应该在componentDidMount()生命周期钩子中的 App(父组件)组件中获取。此外,如果可能,请始终尝试history.push(),因为它不会导致路由更改数据丢失。希望对你有帮助,祝你好运!


推荐阅读