调用 API 的 In componentDidMount 或在单击按钮时调用



我是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。那么,我该如何解决这个问题?

在任何情况下,redux存储中的数据在重新加载后都不会持久存在。你需要有逻辑地处理这个案子。看看这个教程。您应该以这种方式管理数据流。

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

最新更新