javascript - 在 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
。那么,我该如何解决这个问题?
解决方案
在任何情况下,redux 存储中的数据在重新加载后都不会保留。您需要从逻辑上处理这种情况。看看这个教程。您应该以这种方式管理数据流。
简而言之,即使在重新加载之后,您在多个路由上需要的任何数据都应该在componentDidMount()
生命周期钩子中的 App(父组件)组件中获取。此外,如果可能,请始终尝试history.push()
,因为它不会导致路由更改数据丢失。希望对你有帮助,祝你好运!
推荐阅读
- caching - 如何通过标签重置PageCache?如何标记 PageCache?
- ios - 如何在 iOS 上以编程方式设置所有者个人资料紧急信息
- python - 子流程中的子流程。如何在错误时传播输出?
- reactjs - 组件不会重新渲染,但 redux 状态已通过反应钩子改变
- r - 数组上的外部函数产生 rom Vectorize 函数
- php - 此查询与 php 不兼容吗?它有一个明显的语法错误,因为我无法让它运行
- .htaccess - 剪切“?_escaped_fragment_=”并重定向到 html/php
- accessibility - 标签中带有链接的可访问假复选框
- c# - 如何显示路径文件中的图像?
- swift - 如何使包含元组的字典符合可编码的要求?