首页 > 解决方案 > 使用 react-redux-form 提交表单时出现刷新问题

问题描述

问题

重要提示:这已解决;见下面的解释。

我在提交 react-redux-form 时遇到了页面刷新的问题。我发现了很多类似的问题,因为这是在 HTML 中提交表单的默认行为;但是我还没有找到与这个特定库(react-redux-form)相关的任何东西。

我也尝试应用在其他情况下的建议,主要是 event.preventDefault(),但我不知道如何在这个库中使用事件对象,因为他们推荐以下语法:

<LocalForm onSubmit={(values) => this.handleSubmit(values)}>

我尝试过 values.event,但没有成功。

下面是我打算拥有的:

import React, { Component } from 'react';
import Hall from './HallComponent';
import { Row, Button, Label } from 'reactstrap';
import { Redirect } from 'react-router';
import { LocalForm, Control } from 'react-redux-form';

class Endgame extends Component {

  constructor(props) {
    super(props);
    this.state = { 
      redirect: false
    };

    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(values) {
    const date = new Date();
    this.props.addScore({
      date: date.toLocaleDateString("en-GB"),
      name: values.name,
      score: this.props.points
    });
    this.setState({ redirect: true });
  }

  render() {
    if (this.state.redirect) {
      return (
        <Redirect to="/hall" />
      );
    }
    else {
      return(
        <div className="container">
          <div className="row">
            <div className="col-12 col-md-5 m-1">
              <p>Your score is: {this.props.points}</p>
              <p>Add you name to the Hall of Fame</p>
              <LocalForm onSubmit={(values) => this.handleSubmit(values)}>
                <Row className="form-group">
                  <Label htmlFor="name">Nickname</Label>
                  <Control.text model=".name" id="name" name="name" placeholder="Your Name" className="form-control"  />
                </Row>
                <Button type="submit">Submit</Button>
              </LocalForm>
            </div>
            <div className="col-12 col-md-5 m-1">
              <Hall scores={this.props.scores} />
            </div>
          </div>
        </div>
      );
    }
    }

}

export default Endgame;

解决方案

我发现问题不是来自提交按钮,而是我安排组件的方式。我仍然不完全确定幕后实际发生了什么,但我上面的 Hall 组件在每次 addScore() (例如 redux 动作被触发)时被卸载并重新安装。我发现如果父组件的状态以某种方式被修改,这可能会发生这种情况,这可能会触发重新安装子组件。我已将状态本地迁移到将其连接到 redux 存储的 Hall 组件,它现在可以正常工作。

标签: reactjsreduxreact-reduxreact-redux-form

解决方案


这是因为您有一个“提交”类型的按钮。它的默认操作是刷新页面。

                <Button type="submit">Submit</Button>

您可以evt.preventDefault()在句柄提交函数中放置一个来阻止页面刷新,但我建议您只需更改按钮类型并将句柄提交函数放在 onClick 事件上,就像这样。

                <Button type="button" onClick={this.handleSubmit}>Submit</Button>

推荐阅读