在React-Redux中将表单变量传递给动作创建者

时间:2019-03-08 09:41:45

标签: redux

在React-Redux应用程序中,我试图不使用Redux-Form,Formic或任何其他扩展名将表单变量从组件传递给动作创建者。

myForm.js

import { connect } from "react-redux";
import { fetchData } from "../actions/myActions";

class myForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      from: "",
      to: ""
    };
    this.onFormSubmit = this.onFormSubmit.bind(this);
  }

onFormSubmit(event) {
event.preventDefault();

const from = event.target.elements.from.value;
const to = event.target.elements.to.value;

this.setState({
      from: from,
      to: to
    });

    this.props.fetchData(
      this.state.from,
      this.state.to,
    );
  }

render() {
    return (
      <div>
        <form onSubmit={this.onFormSubmit}>
            <div>
            <input
              type="text"
              name="from"
            />
          </div>
          <div>
            <input
              type="text"
              name="to"
            />
          </div>
    </form>
 </div>


    export default connect(
      null,
      { fetchData }
    )(myForm);

我将动作创建者 fetchData 传递给myForm组件,并在表单提交时调用onFormSubmit函数,该函数将表单变量传递给fetchData,如下所示:

this.props.fetchData(
   this.state.from,
   this.state.to,
);

然后在myActions.js中尝试访问这些表单变量并启动API请求。

myActions.js

import { FETCH_DATA } from "./types";
import axios from "axios";
const APP_KEY = <my api key>;

export const fetchData = (from,to) => async dispatch => {
  const response = await axios.get`${URL}/${from}/to/${to}?app_key=${APP_KEY}`;

  dispatch({
    type: FETCH_DATA,
    payload: response.data.journeys
  });
};

我正在尝试正确的方法吗? 不幸的是,变量 from to 似乎没有传递给myAction.js内部的动作创建者。

1 个答案:

答案 0 :(得分:1)

setState是异步操作,因此在状态被设置之前就调用this.props.fetchData。您需要在状态更新后调用的 myForm.js setState的第二个参数中使用回调。

this.setState({
    from: from,
    to: to
}, () => {
    this.props.fetchData(this.state.from,this.state.to)
});

希望这会有所帮助。编码愉快!