简体   繁体   English

防止表单提交时重新加载页面

[英]Prevent page reload on form submission

e.preventDefault() attached to form is not working and when I press save button, the page reloads on submission. 附加到表单的e.preventDefault()无法正常工作,当我按保存按钮时,页面将在提交时重新加载。

I have a seperate Form component that works just fine but I am unable to fix this one. 我有一个单独的Form组件,可以很好地工作,但是我无法修复它。

What am i doing wrong? 我究竟做错了什么? Any help is greatly appreciated. 任何帮助是极大的赞赏。

My code below 我的代码如下

TIA TIA


class Todo extends Component {
  constructor(props){
      super(props);
      this.state = { isEditing: false, task: this.props.task }
      this.handleRemove = this.handleRemove.bind(this);
      this.toggleEdit = this.toggleEdit.bind(this);
      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleChange.bind(this);
    }
  handleRemove () {
      this.props.removeTodo(this.props.id)
  };

  toggleEdit () {
      this.setState ({
          isEditing: !this.state.isEditing
      });
  }
  handleChange(e) {
      this.setState({
          [e.target.name]: e.target.value
      });
  }
  handleSubmit(e) {
      e.preventDefault();
      this.props.updateTodo(this.props.id, this.state.task);
      this.setState({
          isEditing: false
      })
  }
  render() {
   let result; 
    if (this.state.isEditing) {
        result = (
        <div>
            <form onSubmit={this.handleSubmit}>
                <input 
                    type='text'
                    name='task'
                    value={this.state.task}
                    onChange={this.handleChange}
                />
                <button>Save</button>
            </form>
        </div>
            )
    } else {
        result = (
        <div> 
            {this.props.task}
            <button onClick={this.handleRemove}>X</button>
            <button onClick={this.toggleEdit}>E</button>           
        </div>

        )
      }
    return result;
  }
}

export default Todo;

It looks like in your constructor you are binding the function wrong: 看起来在constructor您将函数绑定错误:

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

The second function needs to bind against handleSubmit instead 第二个函数需要绑定到handleSubmit

I think it's first worth noting that without javascript (plain html), the form element submits when clicking either the <input type="submit" value="submit form"> or <button> submits form too </button> . 我认为首先要注意的是,如果没有javascript(纯HTML),则在单击<input type="submit" value="submit form"><button>提交表单</button>也会提交form元素。

In javascript you can prevent that by using an event handler and calling e.preventDefault() on button click, or form submit. 在javascript中,您可以通过使用事件处理程序并在按钮单击或表单提交上调用e.preventDefault()来防止这种情况。 e is the event object passed into the event handler. e是传递给事件处理程序的事件对象。 With react, the two relevant event handlers are available via the form as onSubmit, and the other on the button via onClick . 通过react,两个相关的事件处理程序可以通过onSubmit形式使用,另一个可以通过onClick在按钮上使用。

<Button color="primary" onClick={this.onClickPreventDefault}>onClickPreventDefault</Button>

Example: http://jsbin.com/vowuley/edit?html,js,console,output 示例: http//jsbin.com/vowuley/edit?html,js,console,output

Areas changed: 区域已更改:

  1. Constructor not needed 不需要构造函数
  2. Props was never being used around state, now just props 道具从未在州周围使用过,现在只是道具
  3. No need to create result variable 无需创建result变量
  4. Move towards arrow functions reduces codebase 👌🏻 转向箭头功能可减少代码库👌🏻
  5. Toggle fn() - take from previous props it's faster! 切换fn()-从以前的道具中获取更快!
  6. Submit fn() - fire your props after state change, as setState() is not async 提交fn()-状态更改后触发您的道具,因为setState()不异步

Other area for improvement: 其他需要改进的地方:

  1. You could make this a stateless component with useState() 您可以使用useState()useState()无状态组件

    I hope this helps 👍🏻 我希望这可以帮助👍🏻

class Todo extends Component {
  state = {
    isEditing: false
  };

  handleRemove = () => {
    this.props.removeTodo(this.props.id);
  };

  toggleEdit = () => {
    this.setState(({ isEditing }) => ({
      isEditing: !isEditing
    }));
  };

  handleChange = ({ target }) => {
    this.setState({
      [target.name]: target.value
    });
  };

  handleSubmit = e => {
    e.preventDefault();

    this.setState(
      {
        isEditing: false
      },
      () => {
        this.props.updateTodo(this.props.id, this.props.task);
      }
    );
  };

  render() {
    const { task } = this.props;

    return this.state.isEditing ? (
      <div>
        <form onSubmit={this.handleSubmit}>
          <input
            type="text"
            name="task"
            value={task}
            onChange={this.handleChange}
          />
          <button type="sumbit">Save</button>
        </form>
      </div>
    ) : (
      <div>
        {task}
        <button onClick={this.handleRemove}>X</button>
        <button onClick={this.toggleEdit}>E</button>
      </div>
    );
  }
}

export default Todo;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM