reactjs - 如何提交表单和添加道具的最佳方式是什么?
问题描述
请问,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);
错误:
警告:您试图重定向到您当前所在的同一条路线:
/products
"表单提交因表单未连接而取消
请问如何实现我的目标的最佳方法是什么?
解决方案
您需要取消默认提交操作。
所以改变你handleSubmit
的方法
handleSubmit = (e) => {
e.preventDefault();
this.setState({
toDashboard: true
});
}
推荐阅读
- azure - Azure IOT Edge 设备能否连接到多个 Azure IOT Hub?
- dictionary - 增加可变映射值会导致可为空的接收器错误
- c# - 将连字字符放入 ComboBox 文本
- reactjs - Redux 表单无法输入
- java - 创建一个将采用 jsonPath 和类型的验证,检查 jsonpath 和类型的数据类型是否相同
- android - 更改 Recyclerview 背景颜色会使工具栏消失 - 为什么会这样
- javascript - 如何使用 jQuery 搜索嵌套的 JSON 数组?
- python - 如何用python找到一个数的质因数
- mysql - Mysql while 循环不工作(返回 1064)
- python - 为什么一个全局列表更新为与另一个相同的值,即使它们从未被告知相等?