如何在带有Rails后端的react-redux中获取表单提交值?

时间:2019-09-02 22:03:51

标签: javascript forms react-redux action dispatch

我有一个Rails后端,上面列出了成分列表。我正在尝试使用搜索栏(窗体)输入成分ID以查找适当的成分。     当我单击表单的提交按钮时,我希望使用ID作为参数的分派函数getIngredient,但是使用我尝试过的方法,我没有得到应该是ID的东西。它是未定义的,或者仅仅是“一个事件”。我只是短暂地看到了错误消息,所以我没有更多的细节了。它只是刷新状态,清除错误消息。

我尝试使用onSubmit={() => getIngredient(id)}形式的值,然后将其作为事件对象返回。与onSubmit={() => this.props.getIngredient(id)}一起返回未定义。仅将其表示为onSubmit={getIngredient(id)}也不起作用。

我已将console.log记录为所有内容,并且发现它在getIngredient(id)中执行调度操作时出错,因为id是未定义的。

我使用的getIngredients方法有效,这是在尝试仅获取我遇到麻烦的一种成分时。我已经阅读了有关redux,react-redux甚至可以重新选择以解决该问题的所有信息,而我碰到了这堵墙。

IngredientForm.js组件:

        <form onSubmit={(id) => getIngredient(id)}>
          <label value="Find Ingredient">
            <input type="text" placeholder="Search By Id" />
          </label>
          <input type="submit" value="Find Ingredient" />
        </form>

const mapDispatchToProps = { getIngredient }

const mapStateToProps = (state, props) => {
  const id = props.id;
  return {
    ingredients: state.ingredients.filter(ingredient => ingredient.id === id)
  };
};

在actions.js中调度动作创建者:

export function getIngredient(id) {
  return dispatch => {
        console.log("trying to get id to show up =>", id)
    dispatch(getIngredientRequest(id));
    return fetch(`v1/ingredients`)
      .catch(error => console.log(error))
      .then(response => response.json())
      .then(json => dispatch(getIngredientSuccess(json)))
      .catch(error => console.log(error));
  }
}

动作:

export function getIngredientRequest(id) {
  return { type: GET_INGREDIENT_REQUEST, id };
}

reducer.js

function rootReducer(state = initialState, action) {
  console.log(action.type);
  switch (action.type) {
    case "GET_INGREDIENTS_SUCCESS":
      return { ...state, ingredients: action.json.ingredients }
    case "GET_INGREDIENTS_REQUEST":
      console.log('Ingredients request received')
      return
    case "HIDE_INGREDIENTS":
      console.log('Ingredients are being hidden')
      return { ...state, ingredients: [] }
    case "GET_INGREDIENT_REQUEST":
      console.log('One Ingredient request received:', "id:", action.id)
      return
    case "GET_INGREDIENT_SUCCESS":
    console.log('GET_INGREDIENT_SUCCESS')
      return {
                ...state,
                ingredients: action.json.ingredients.filter(i => i.id)
            }
    default:
      return state
  }
}

服务器终端窗口输出:

Processing by StaticController#index as HTML
  Parameters: {"page"=>"ingredients"}
  Rendering static/index.html.erb within layouts/application
  Rendered static/index.html.erb within layouts/application (0.9ms)
Completed 200 OK in 9ms (Views: 7.9ms | ActiveRecord: 0.0ms)```

1 个答案:

答案 0 :(得分:0)

那是因为在React Synthetic Events中-像onSubmit-回调中的第一个参数始终是Event对象。 我建议您使用受控输入。这意味着您将id值保持在组件的状态,并将该值分配给输入。每当用户键入新的ID时,您都会更新状态并将新值分配给输入。

class Form extends React.Component {
 state = {
  id: ""
 };

 handleInputChange = event => {
  this.setState({ id: event.target.value });
 };

 render() {
  return (
   <form
    onSubmit={(event) => {
     event.preventDefault();
     getIngredient(this.state.id);
    }}
   >
    <label value="Find Ingredient">
     <input
      type="text"
      placeholder="Search By Id"
      onChange={this.handleInputChange}
      value={this.state.id}
     />
    </label>
    <input type="submit" value="Find Ingredient" />
   </form>
  );
 }
}