ReactJS: необработанное отклонение (TypeError): невозможно прочитать свойство 'pu sh' из неопределенного - PullRequest
0 голосов
/ 27 марта 2020

enter image description here

После использования формы и вставки новых данных появляется эта ошибка.

Это мой код:

import React from "react";
import { Form, Input, Button } from "antd";
import { connect } from "react-redux";
import axios from "axios";

import hashHistory from './hashHistory';


const FormItem = Form.Item;




class CustomForm extends React.Component {

  handleFormSubmit = async (event, requestType, articleID) => {
    event.preventDefault();

    const postObj = {
      title: event.target.elements.title.value,
      content: event.target.elements.content.value
    }

    axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
    axios.defaults.xsrfCookieName = "csrftoken";
    axios.defaults.headers = {
      "Content-Type": "application/json",
      Authorization: `Token ${this.props.token}`,
    };

    if (requestType === "post") {
      await axios.post("http://192.168.196.49:8000/api/create/", postObj)
        .then(res => {
          if (res.status === 201) {
            //this.props.history.push(`/articles/`);
            //this.props.hashHistory.push('/');
            //hashHistory.push(String('/articles/'))
            this.props.history.push({
              pathname: "/"
           })

          }
        })
    } else if (requestType === "put") {
      await axios.put(`http://192.168.196.49:8000/api/${articleID}/update/`, postObj)
        .then(res => {
          if (res.status === 200) {
            //this.props.history.push(`/articles/`);
            //this.props.hashHistory.push('/');
            //hashHistory.push(String('/articles/'))
            this.props.history.push({
              pathname: "/"
           })
          }
        })
    }
  };

  render() {

    console.log("debug:", this.props)

    return (
      <div>
        <Form
          onSubmit={event =>
            this.handleFormSubmit(
              event,
              this.props.requestType,
              this.props.articleID
            )
          }
        >
          <FormItem label="Título">
            <Input name="title" placeholder="Put a title here" />
          </FormItem>
          <FormItem label="Comentario">
            <Input name="content" placeholder="Enter some content ..." />
          </FormItem>
          <FormItem>
            <Button type="primary" htmlType="submit">
              {this.props.btnText}
            </Button>
          </FormItem>
        </Form>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    token: state.token
  };
};

export default connect(mapStateToProps)(CustomForm);

Маршруты

 <Route exact path="/articles/" component={ArticleList} />{" "} 
 <Route exact path="/articles/:articleID/" component={ArticleDetail} />{" "}

Сообщение об ошибке:

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined

Данные правильно хранятся в базе данных, но сразу после отправки появляется эта ошибка.

В моем исходном коде использовался history.pu sh, но я пытался использовать hashHistory.pu sh.

Я использую в проекте избыточный текст.

Проверка с использованием: Реактив-роутер 5.1.2 история 4.9.0

Ответы [ 3 ]

0 голосов
/ 27 марта 2020

Вы можете использовать withRouter в pu sh историю в реквизите.

import { withRouter } from 'react-router';

const SpecialButton = withRouter(({ history, path, text }) => {
  return (
    <Button
      onClick={() => { history.push(path); }}
    >
      {text}
    </Button>
  )
});
0 голосов
/ 28 марта 2020

Это было решение, которое работает (может быть, не самое лучшее ...)

код:

import React from "react";
import { Form, Input, Button } from "antd";
import { connect } from "react-redux";
import axios from "axios";
import { createHashHistory } from 'history'


const FormItem = Form.Item;

class CustomForm extends React.Component {

  handleFormSubmit = async (event, requestType, articleID) => {
    event.preventDefault();

    const postObj = {
      title: event.target.elements.title.value,
      content: event.target.elements.content.value
    }

    axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
    axios.defaults.xsrfCookieName = "csrftoken";
    axios.defaults.headers = {
      "Content-Type": "application/json",
      Authorization: `Token ${this.props.token}`,
    };

    const history = createHashHistory();

    if (requestType === "post") {
      console.log("debug_1.1_Form_post_history: ", history )
      await axios.post("http://192.168.196.49:8000/api/create/", postObj)
        .then(res => {
          if (res.status === 201) {
            history.push("/articles/")
          }
        })
    } else if (requestType === "put") {
      console.log("debug_1.2_Form_put_history: ", history )
      await axios.put(`http://192.168.196.49:8000/api/${articleID}/update/`, postObj)
        .then(res => {
          if (res.status === 200) {
          console.log("debug_1.3_Form_put_this.props: ", this.props)
              history.push("/articles/");
          }
        })
    }
  };

  render() {
    return (
      <div>
        <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>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    token: state.token
  };
};

export default connect(mapStateToProps)(CustomForm);
0 голосов
/ 27 марта 2020

Попробуйте сделать модуль hashHistory:

// hashHistory.js
import { createHashHistory } from 'history'; // worked for the OP
export default createHashHistory({}); 

И используйте его:

const history = createHashHistory();
// ....

 // **EDIT** This should work
 history.push("/articles/")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...