首页 > 解决方案 > React 使用 Redux-form , post 方法

问题描述

今天我想用 redux 表单在我的数据库中发布一些数据,我的控制台中有这些值,但我真的不明白如何发布新广告

编辑

使用 this.props.getAdverts()刷新提交并 this.props.addAdvert()在我的提交中发布广告解决了问题

有任何想法吗?

有我的代码

首先我有动作 Action :

export function addAdvert(data) {
  return dispatch => {
    return fetch("adverts", {
      method: "post",
      body: JSON.stringify(data),
      headers: {
        "Content-Type": "application/json"
      }
    });
  };
}

广告形式:

import { Field, reduxForm } from "redux-form";
import React, { Component } from "react";

class AdvertForm extends Component {
  submit() {
    //this
  }

  render() {
    const { handleSubmit } = this.props;
    return (
      <form onSubmit={handleSubmit}>
        <div>
          <label htmlFor="name"> Name</label>
          <Field name="name" component="input" type="text" />
        </div>
        <div>
          <label htmlFor="surname">SurName</label>
          <Field name="surname" component="input" type="text" />
        </div>
        <button type="submit">Submit</button>
      </form>
    );
  }
}

AdvertForm = reduxForm({
  form: "advert"
})(AdvertForm);

export default AdvertForm;

我的页面(广告)我不知道这是否是在这里调用 addAdvert 函数的好方法

//imports

    class Adverts extends Component {
      constructor() {
        super();
        this.state = {
          showForm: false
        };
      }
      submit = values => {
        console.log(values); //the console log above
        this.state.addAdvert(values);
        this.props.getAdverts()
      };
      onClick(e) {
        e.preventDefault();
        this.setState({ showForm: !this.state.showForm });
      }

      componentDidMount() {
        this.props.getAdverts();
      }

      render() {
        const { adverts = [] } = this.props;

        return (
          <div>

            //ADVERTSLIST
            <div className="add-advert-btn">
              <Button
                variant="fab"
                onClick={this.onClick.bind(this)}
                color="primary"
                aria-label="add"
              >
                <AddIcon />
              </Button>
            </div>
            {this.state.showForm && <AdvertForm onSubmit={this.submit} />}

          </div>
        );
      }
    }

    const mapStateToProps = state => ({
      adverts: state.todos.adverts
    });

    export default connect(
      mapStateToProps,
      { getAdverts, addAdvert }
    )(Adverts);

标签: reactjspostreduxreact-reduxredux-form

解决方案


推荐阅读