联系数据.js
import React, { Component } from 'react';
import Button from '../../../components/UI/Button/Button';
import classes from './ContactData.module.css'
class ContactData extends Component {
state = {
name: '',
age: '',
address: {
street: '',
postalCode: ''
}
}
orderHandler = () => {
console.log(this.props.ingredients)
}
render() {
console.log(this.props.ingredients);
return (
<div className={classes.ContactData}>
<h4>Enter Your Contact Data</h4>
<form>
<input type="text" name="name" placeholder="Your Name" />
<input type="email" name="email" placeholder="Your Mail" />
<input type="text" name="street" placeholder="Street" />
<input type="text" name="postal" placeholder="Postal Code" />
<Button btnType="Success" clicked={this.orderHandler}>ORDER</Button>
</form>
</div>
);
}
}
export default ContactData;
CheckOut.js
import React from 'react';
import CheckoutSum from '../../components/Checkout/Checkout'
import { Route } from 'react-router-dom';
import ContactData from '../../container/Checkout/ContactData/ContactData'
class Checkout extends React.Component {
state = {
ingredients: {
salad: 1,
meat: 1,
cheese: 1,
bacon: 1
}
}
componentDidMount() {
const query = new URLSearchParams(this.props.location.search);
const ingredients = {};
for (let param of query.entries()) {
ingredients[param[0]] = parseInt(param[1]);
}
// console.log(ingredients);
this.setState({ ingredients: ingredients });
}
cancelHandle = () => {
this.props.history.goBack();
}
continueHandle = () => {
this.props.history.replace('/checkout/contact-data');
}
render() {
console.log(this.props)
console.log(this.state.ingredients)
return (
<div>
<CheckoutSum
cancel={this.cancelHandle}
continue={this.continueHandle}
ingredients={this.state.ingredients}
/>
<Route
path={this.props.match.path + '/contact-data'}
exact
render={() => (<ContactData ingredients={this.state.ingredients} />)} />
</div>
);
}
}
export default Checkout;
问题是当我点击CotanctData组件中的订单按钮时,页面重新加载,但不知为何我的URL却变成了这个样子。 http:/localhost:3000checkoutcontact-data?name=&email=&street=&postal=。 然后Checkout组件再次渲染,并且由于某些原因,componentDidMount发生了两次。最后我期待的是打印 ingredients 对象。
另外,我在URL中使用搜索查询来改变结账组件的状态。
全项目在https:/github.comaniket-hueBurger-App-ReacttreeRoutes。
如果你不喜欢这个问题,请忍耐一下,我不知道如何构思这个问题。
你需要或者。
e.preventDefult()
在...上 <form>
的提交事件。<button type="button">
的按钮,使其不 submit
你的表格。你必须添加 preventDefault
对你的 orderHandler
方法,因为如果表单中的按钮没有类型,那么类型就会自动被 submit
所以,每点击一次,你就提交一个表格。另外,你可以添加 type="button"
对你的 button
内形。
orderHandler = e => {
e.preventDefault();
console.log(this.props.ingredients);
}