Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在离开组件之前调用函数?_Reactjs_React Redux - Fatal编程技术网

Reactjs 如何在离开组件之前调用函数?

Reactjs 如何在离开组件之前调用函数?,reactjs,react-redux,Reactjs,React Redux,我是一个新手,我正在为REST-API开发一个前端 我的REST-API前端由5个站点(组件)组成,它们通过react router dom路由 每次我进入一个站点时,ComponentDidLoad都会发送一个操作,该操作反过来调用我的reducer中的API export function getData(pURL, ...pParams){ return (dispatch) => { axios.get(pURL, {pParams}) .

我是一个新手,我正在为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); 
或者直接将
isLoading
设置为true,以避免我的站点试图使用旧回迁的数据

有没有办法做到这一点?
我希望我提供了足够的信息,如果没有,请告诉我。

如果您想在离开某个组件时调用该函数,您可以使用
componentWillUnmount
函数。阅读有关React生命周期方法的更多信息

我试着这么做。遗憾的是,这种方式似乎太“慢”,因为当我在
组件中调用我的
this.props.resetStore()
时,当我到达站点时,isLoading仍然是错误的。只有当我已经到达下一个站点的
render()
时,它才会成为现实。您是否需要将
isLoading
标志保存在redux存储中?最好将
isLoading
标志置于状态。这样,当进入站点时,它总是自动为真。。但是我该如何修改这个标志呢?你可以使用承诺。例如:
componentDidMount(){this.props.getData(MyURLHere)。然后(()=>this.setState({isload:false})}
和您的
getData
函数:
导出函数getData(pURL,.pParams){return axios.get(pURL,{pParams})。然后(result=>catch(error=>{dispatch(getDataFailure(error))}
但是当你配置你的商店时,你需要添加中间件,例如
redux thunk
它可以工作!刚刚在我的操作中添加了额外的返回,并在
componentDidMount
中添加了额外的一行。我将尝试了解它的实际工作原理。非常感谢!
const initialStateAPI = {
    isLoading: true
}