【问题标题】:Passing form variables to action creator in React-Redux在 React-Redux 中将表单变量传递给动作创建者
【发布时间】:2019-03-08 19:00:23
【问题描述】:

在 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
  });
};

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

【问题讨论】:

    标签: redux


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 2017-11-26
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      • 2017-07-31
      • 2016-07-30
      相关资源
      最近更新 更多