如何在Next.js的类组件内部实现页面重定向?
实现类组件中的页面重定向
要在你的CampaignNew类组件的onSubmit方法里完成页面重定向,有两种常用方案,无需改成函数组件:
方案一:直接使用props.history(组件已被Route直接渲染)
如果你的CampaignNew是通过React Router的<Route>组件直接渲染的(比如路由配置里写<Route path="/campaign/new" component={CampaignNew} />),组件会自动接收history属性,直接在合约创建成功后添加跳转代码即可:
修改onSubmit方法的对应位置:
await factory.methods.createCampaign(this.state.minimumContribution).send({ from: accounts[0], }); // 执行页面重定向到根路径 this.props.history.push('/'); this.setState({ loading: false });
方案二:用withRouter高阶组件(组件未被Route直接渲染)
如果组件不是直接被<Route>渲染,无法直接拿到history,可以通过React Router提供的withRouter高阶组件注入路由属性:
- 先导入
withRouter:
import { withRouter } from 'react-router-dom';
- 修改组件导出语句,用
withRouter包裹:
export default withRouter(CampaignNew);
- 之后就能在
onSubmit方法里用this.props.history.push('/')完成跳转,写法和方案一一致。
修改后的完整代码
import React, { Component } from "react"; import Layout from "../../components/layoyt"; import { Form, Button, Input, Message } from "semantic-ui-react"; import factory from "../../components/factory"; import web3 from "../../components/web3"; // 导入withRouter(方案二需要) import { withRouter } from 'react-router-dom'; class CampaignNew extends Component { state = { minimumContribution: "0", errorMessage: "", loading: false, }; onSubmit = async (event) => { event.preventDefault(); this.setState({ loading: true, errorMessage: "" }); try { await window.ethereum.enable(); const accounts = await web3.eth.getAccounts(); console.log("Account :" + accounts[0]); await factory.methods.createCampaign(this.state.minimumContribution).send({ from: accounts[0], }); // 执行页面重定向到根路径 this.props.history.push('/'); this.setState({ loading: false }); } catch (err) { this.setState({ errorMessage: err.message }); this.setState({ loading: false }); } }; render() { return ( <Layout> <h3>Create a Campaign</h3> <Form onSubmit={this.onSubmit} error={!!this.state.errorMessage}> <Form.Field> <label>Minimum Contribution</label> <Input label="wei" labelPosition="right" value={this.state.minimumContribution} onChange={(event) => this.setState({ minimumContribution: event.target.value })} /> </Form.Field> <Message error header="There was some errors with your submission" content={this.state.errorMessage} /> <Button loading={this.state.loading} primary> Create </Button> </Form> </Layout> ); } } // 用withRouter包裹组件(方案二需要) export default withRouter(CampaignNew);
注:确保你的项目已安装并配置React Router v5(v6中withRouter已被移除,若使用v6类组件需用其他方式适配,但这类Dapp项目通常用v5较多)。
内容的提问来源于stack exchange,提问作者Pablo Rego
相关产品推荐
相关产品推荐

