首页 > 解决方案 > 如何提交表单和添加道具的最佳方式是什么?

问题描述

请问,React如何实现的最佳方法是什么:

我发现了两种重定向的可能性:

来源文章:https ://tylermcginnis.com/react-router-programmatically-navigate/

1)使用反应路由器:history.push()

2)使用反应路由器:<Redirect />


1)使用history.push():重定向有效,但我不知道如何将自定义道具添加到重定向页面。

2)使用<Redirect />:添加自定义道具作品(以这种方式):

<Redirect to={{ pathname: '/products', state: { id: '123' } }} />

但是重定向对我不起作用,提交后我一直收到错误。

源代码:

import React from 'react';
import './App.css';
import { withRouter, Redirect } from 'react-router-dom'

class App extends React.Component {

    state = {
        toDashboard: false,
    }
    handleSubmit = () => {
        this.setState(() => ({
            toDashboard: true
        }));
    }
    render() {
        if (this.state.toDashboard === true) {
            return <Redirect to={{
                pathname: '/products', state: { id: '123' }
            }} />
        }

        return (
            <div>
                <h1>Register</h1>
                <form onSubmit={this.handleSubmit}>
                    <button type="submit">Submit</button>
                </form>
            </div>
        );
    }
}
export default withRouter(App);

错误:

在此处输入图像描述

请问如何实现我的目标的最佳方法是什么?

标签: reactjs

解决方案


您需要取消默认提交操作。

所以改变你handleSubmit的方法

handleSubmit = (e) => {
    e.preventDefault();
    this.setState({
        toDashboard: true
    });
}

推荐阅读