nwa*_*arp 3 javascript next.js
我有一个页面getInitialProps()在 2 秒后生成一个随机数。有一个按钮允许用户通过Router.push(). 由于getInitalProps()需要 2 秒才能完成,我想显示一个加载指示器。
import React from 'react'
import Router from 'next/router'
export default class extends React.Component {
state = {
loading: false
}
static getInitialProps (context) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({random: Math.random()})
}, 2000)
})
}
render() {
return <div>
{
this.state.loading
? <div>Loading</div>
: <div>Your random number is {this.props.random}</div>
}
<button onClick={() => {
this.setState({loading: true})
Router.push({pathname: Router.pathname})
}}>Refresh</button>
</div>
}
}
Run Code Online (Sandbox Code Playgroud)
我如何知道何时Router.push()/getInitialProps()完成以便清除加载指示器?
编辑:使用Router.on('routeChangeComplete')是最明显的解决方案。但是,有多个页面,用户可以多次单击该按钮。有没有安全的方法来为此使用路由器事件?
use 可以使用Router事件监听器pages/_app.js,管理页面加载并将状态注入组件
import React from "react";
import App, { Container } from "next/app";
import Router from "next/router";
export default class MyApp extends App {
state = {
loading: false
};
componentDidMount(props) {
Router.events.on("routeChangeStart", () => {
this.setState({
loading: true
});
});
Router.events.on("routeChangeComplete", () => {
this.setState({
loading: false
});
});
}
static async getInitialProps({ Component, ctx }) {
let pageProps = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx);
}
return { pageProps };
}
render() {
const { Component, pageProps } = this.props;
return (
<Container>
{/* {this.state.loading && <div>Loading</div>} */}
<Component {...pageProps} loading={this.state.loading} />
</Container>
);
}
}
Run Code Online (Sandbox Code Playgroud)
并且您可以将加载作为页面组件中的道具进行访问。
import React from "react";
import Router from "next/router";
export default class extends React.Component {
static getInitialProps(context) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ random: Math.random() });
}, 2000);
});
}
render() {
return (
<div>
{this.props.loading ? <div>Loading</div> : <div>Your random number is {this.props.random}</div>}
<button
onClick={() => {
this.setState({ loading: true });
Router.push({ pathname: Router.pathname });
}}
>
Refresh
</button>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
您还可以在(我评论过)中显示加载文本_app.js,这样您就不必检查每个页面的加载状态
如果你想在这里使用第三方包,nprogress是一个不错的选择
Router.push()返回一个 Promise。所以你可以做一些像......
Router.push("/off-cliff").then(() => {
// fly like an eagle, 'til I'm free
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7834 次 |
| 最近记录: |