簡體   English   中英

與React-Router一起管理加載條的狀態

[英]Managing state for a loading bar in react with react-router

我在React中有一個應用程序,它使用了Material-ui的響應式抽屜組件。 我們稱它為ResponsiveDrawer。 在此組件中,我有一個狀態變量稱為“ loading”。

class ResponsiveDrawer extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading:false
        }
        this.setLoading = this.setLoading.bind(this);
    }
    setLoading(loading) {
        this.setState({loading:loading});
    }
    ...

我想在頁面頂部顯示LinearProgress組件,具體取決於loading狀態變量。

    ...
    render() {
        return (
            <div className={classes.root}>
                {this.state.loading ? <LinearProgress/> : ""} 
                ...

在ResponsiveDrawer內部,我還使用React Router渲染一些子組件。

                ...
                <main className={classes.content}>
                    <div className={classes.contentWrapper}>
                        <Switch>
                            <Route
                                exact
                                path="/investments"
                                component={InvestmentsComponent}
                            />
                            ...
                        </Switch>
                     </div>
               </main>
          </div>

在投資組件內部,我正在從API中提取數據。 我想做的是將ResponsiveDrawer組件中的加載狀態設置為true ,然后在成功獲取后將其設置為false

因此,我將ResponsiveDrawer的setLoading函數作為props傳遞給InvestmentsComponent:

 InvestmentsComponent = <Investments setLoading={this.setLoading} />

然后嘗試在componentDidMount()上將其設置為true

    componentDidMount() {
        this.props.setLoading(true);
        fetchInvestments(); // sets loading to false upon completion
    }

     fetchInvestments() {
        fetch("/api/investments", {
            credentials: "same-origin",
            headers: {
                "Cache-Control": "no-cache"
            }
        })
            .then(res => {
                if (!res.ok) throw Error(res.status);
                return res.json();
            })
            .then(responseJson => {
                this.props.setLoading(false);
                this.setState({ investments: responseJson });
            })
            .catch(err => {
                console.error("Unable to fetch investments"); // show error message
            });
    }

但是,當我這樣做時,反應會陷入無限循環-我假設當loading狀態發生變化時,它還會重新加載投資組件路線,然后再次設置加載狀態。

我最終得到:

超過最大更新深度。 當組件重復調用componentWillUpdate或componentDidUpdate內部的setState時,可能會發生這種情況。 React限制了嵌套更新的數量,以防止無限循環。

有什么可能解決這個難題?

我實際上是通過使用另一種方式渲染路線組件來解決此問題的,方法是使用render而不是component prop

 <Route exact path="/investments" render={InvestmentsComponent} />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM