反应-发布后出现错误响应时不刷新页面

时间:2019-08-24 08:32:35

标签: javascript reactjs

我有一个应用程序,它从服务器获取数据,该数据是用nodeJS编写的。 我使用componentDidMount获取数据。在页面上输入名称来命名带有数据的表,并且每一行都有复选框。当我单击“发送”按钮时,选定的行将在后端发送。在后端,我验证唯一名称。如果不是,则返回错误。但面对的是​​每一次刷新。并且不可能得到错误消息。

import React, {Component} from 'react';
import axios from 'axios';
import MyNavbar from "./MyNavbar";

class Offer extends Component {
    constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleCheckedOrder = this.handleCheckedOrder.bind(this);
        this.state = {
            offers: [],
            name: '',
            selectedFoods: [],
            selectedBuild: 'Nevybráno',
            isOrderChecked: false
        };
    }

    componentDidMount() {
        this.getOffer();
    }

    getOffer() {
        const url = '/offer';
        axios.get(url).then(response => {
            this.setState({offers: response.data})
        }).catch(() => 'Cannot load menu');
    };

    handleNameChange = evt => {
        this.setState({name: evt.target.value});
    };

    handleChecboxChange = offer => {
        if (this.state.selectedFoods.includes(offer)) {
            this.setState({selectedFoods: this.state.selectedFoods.filter(item => item !== offer)});
        } else {
            this.setState({selectedFoods: [...this.state.selectedFoods, offer]});
        }
    };

    handleCheckedOrder() {
        this.setState({isChecked: !this.state.isChecked});
    }

    isValid() {
        let isEnabledSubmit = this.state.name.length > 0;
        let isSelectedFoodAndNotOnlySoap = this.state.selectedFoods.length > 0 && this.state.selectedFoods.some(food => food.index !== 0);
        let isSelectedBuild = this.state.selectedBuild !== 'Nevybráno';
        return isEnabledSubmit && isSelectedFoodAndNotOnlySoap && isSelectedBuild;
    }

    handleSubmit() {
        axios({
            method: 'post',
            url: '/order',
            headers: {},
            data: {
                name: this.state.name,
                food: this.state.selectedFoods,
                order: this.state.isChecked,
                build: this.state.selectedBuild
            }
        });
    };

    render() {
        const {offers} = this.state;
        const options = ["Nevybráno", "A", "B"];

        return (
            <div>
                <MyNavbar/>
                <div className="container">
                    <form className="form-inline justify-content-center" onSubmit={this.handleSubmit}>
                        <table className="table">
                            <tbody>
                            <tr>
                                <th>&nbsp;</th>
                                <th>#</th>
                                <th>Váha</th>
                                <th>Menu</th>
                                <th>Cena</th>
                            </tr>
                            {offers.map((offer) => {
                                return (
                                    <tr key={offer.index}>
                                        <td style={{width: '5%'}}>
                                            <input type="checkbox" className="checkbox"
                                                   onChange={this.handleChecboxChange.bind(this, offer)}/>
                                        </td>
                                        <td style={{width: '5%'}}>{offer.index}</td>
                                        <td style={{width: '10%'}}>{offer.weight}g</td>
                                        <td style={{width: '70%'}}>{offer.name}</td>
                                        <td style={{width: '20%'}}>{offer.discount} Kč</td>
                                    </tr>
                                )
                            })}
                            </tbody>
                        </table>

                        <label className="sr-only" htmlFor="inlineFormInput">Name</label>
                        <input type="text" className="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput"
                               placeholder="Jméno" onChange={this.handleNameChange}/>

                        <label className="mr-sm-2" htmlFor="inlineFormCustomSelect">Budova</label>
                        <select className="custom-select mb-2 mr-sm-2 mb-sm-0" id="inlineFormCustomSelect"
                                onChange={(e) => this.setState({selectedBuild: e.target.value})}>
                            {options.map(option => {
                                return <option value={option} key={option}>{option}</option>
                            })}
                        </select>

                        <div className="form-check mb-2 mr-sm-2 mb-sm-0">
                            <label className="form-check-label">
                                <input className="form-check-input" type="checkbox"
                                       onChange={this.handleCheckedOrder}/> Objednám
                            </label>
                        </div>

                        <button type="submit" className="btn btn-secondary"
                                disabled={!this.isValid()}>Odeslat
                        </button>
                    </form>
                </div>
            </div>
        );
    }
}

export default Offer;

3 个答案:

答案 0 :(得分:4)

这是因为默认情况下,按钮提交表单并刷新页面。这可以通过使用evt.preventDefault();

来防止
handleSubmit(evt) {
    evt.preventDefault();
    axios({
        method: 'post',
        url: '/order',
        headers: {},
        data: {
            name: this.state.name,
            food: this.state.selectedFoods,
            order: this.state.isChecked,
            build: this.state.selectedBuild
        }
    });
};

答案 1 :(得分:2)

除了maartendev's注释之外,要获取错误并导致组件状态,您可以将处理程序编写为:

handleSubmit(evt) {
  evt.preventDefault();
  axios({
    method: 'post',
    url: '/order',
    headers: {},
    data: {
        name: this.state.name,
        food: this.state.selectedFoods,
        order: this.state.isChecked,
        build: this.state.selectedBuild
    }
   }).catch(({ response }) => this.setState({ errors: response.data }));
}

这将为您提供this.state.errors中的错误,可以在渲染方法中使用。

答案 2 :(得分:0)

尝试将其添加为表单function evt.preventDefault();}

handleSubmit=(eve)=>
{
  evt.preventDefault();
}

告诉我是否可行。