我对 React 有点陌生,我正在开发 REST-API 的前端。
我的 REST-API 前端由 5 个站点(组件)组成,这些站点通过 react-router-dom
进行路由。
每次我进入站点时,ComponentDidLoad
都会调度一个操作,该操作又会调用我的 reducer 中的 API。
export function getData(pURL, ...pParams){
return (dispatch) => {
axios.get(pURL, {pParams})
.then(result => {
dispatch(getDataSuccess(result.data))
})
.catch(error => {
dispatch(getDataFailure(error))
})
}
}
我的一个主要网站如下所示
class Overview extends Component {
componentDidMount(){
this.props.getData(MyURLHere);
}
render(){
return(
<div>
{this.props.hasError ? "Error while pulling data from server " : ""}
{/* isLoading comes from Store. true = API-Call in Progress */}
{this.props.isLoading ? "Loading Data from server" : this.buildTable()}
</div>
)
}
}
let mapStateToProps = state => {
hasError: state.api.hasError,
isLoading: state.api.isLoading,
companies: state.api.fetched
}
let mapDispatchToProps = {
//getData()
}
export default connect(mapStateToProps, mapDispatchToProps)(Overview);
state.api.fetched
是我的存储变量,我存储来自每个 API 调用的数据。
this.buildTable()
只是映射数据并创建一个简单的 HTML-Table
我的问题是我在 initialState
中将存储状态变量 isLoading
设置为 true
。
但是当我移动到另一个站点然后返回到这个站点时,它会自动从 state.api.fetched
获取数据并尝试使用 this.buildTable()
它,因为 isLoading
不是 true
。这以“不是函数”错误结束,因为其中仍然存在从另一个站点获取的旧数据。
我的解决方案是在离开组件(站点)时始终调用一个函数,将我的商店重置为其initialState
const initialStateAPI = {
isLoading: true
}
或直接将 isLoading
设置为 true,以避免我的网站尝试使用旧提取的数据。
有办法吗? 我希望我提供了足够的信息,如果没有,请告诉我。
最佳答案
如果你想在离开组件时调用该函数,可以使用componentWillUnmount
函数。阅读有关 React 生命周期方法的更多信息。
关于reactjs - 如何在离开组件之前调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52715986/