默认页面重新加载后不会执行事件代码

问题描述 投票:0回答:2

在onSubmit表单事件中,我想用PUT或POST方法将一些数据发送到服务器,然后刷新页面,但页面重新加载而不执行其余的事件代码。添加行event.preventDefault()修复了问题但阻止了重新加载。我错过了什么?

活动代码:

handleFormSubmit = (event, requestType, articleID) => {
        const title = event.target.elements.title.value;
        const content = event.target.elements.content.value;
        switch ( requestType ) {
            case 'post':
                return axios.post('http://127.0.0.1:8000/api/', {
                    title: title,
                    content: content
                })
                .then(res => console.log(res))
                .catch(error => console.err(error));
            case 'put':
                return axios.put(`http://127.0.0.1:8000  /api/${articleID}/`, {
                    title: title,
                    content: content
                })
                .then(res => console.log(res))
                .catch(error => console.err(error));
        }
    }

表格代码:

 <Form onSubmit={(event) => this.handleFormSubmit(
                event,
                this.props.requestType,
                this.props.articleID )}>
            <FormItem label="Title" >
                <Input name="title" placeholder="Put a title here" />
            </FormItem>
            <FormItem label="Content" >
                <Input name="content" placeholder="Enter some content ..." />
            </FormItem>
            <FormItem>
                <Button type="primary" htmlType="submit">{this.props.btnText}</Button>
            </FormItem>
            </Form>
reactjs event-handling dom-events
2个回答
1
投票

您需要在成功提交表单后以编程方式重新加载页面,或者在没有响应或任何服务器错误时显示错误消息:

class App extends React.Component {
  handleSubmit = e => {
    e.preventDefault();
    return axios
      .post("https://reqres.in/api/login", {
        email: "title",
        password: "content"
      })
      .then(res => {
        alert(res.data.token);
        location.reload();
      })
      .catch(error => console.log(error));
  };

  render() {
    return (
      <div className="App">
        <form onSubmit={this.handleSubmit}>
          <input type="text" placeholder="Email" />
          <input type="password" placeholder="Password" />
          <button type="submit">Submit</button>
        </form>
      </div>
    );
  }
}

这是一个演示:https://codesandbox.io/s/j7j00nq705


0
投票

你可以使用event.preventDefault()。但是您应该在请求完成后使用react-routerhistory.push()手动加载另一个组件。

  case 'post':
             return axios.post('http://127.0.0.1:8000/api/', {
                    title: title,
                    content: content
             })
             .then(res => {
                  console.log(res);
                  // using "history.push()" to load another component
                  this.props.history.push('/somePage')
                  })
             .catch(error => console.err(error));

您的上述Form组件必须使用react-router进行路由,或者Form组件必须使用react-router路由到Component

© www.soinside.com 2019 - 2024. All rights reserved.