簡體   English   中英

如何在帶有Rails后端的react-redux中獲取表單提交值?

[英]How to get Form submit value in react-redux with rails backend?

我有一個Rails后端,其中列出了成分列表。 我正在嘗試使用搜索欄(窗體)輸入成分ID以查找適當的成分。 當我單擊表單的提交按鈕時,我希望使用ID作為參數的分派函數getIngredient,但是使用我嘗試過的方法,我沒有得到應該是ID的東西。 它是未定義的,或者僅僅是“一個事件”。 我只是短暫地看到了錯誤消息,所以我沒有更多的細節了。 它只是刷新狀態,擦除錯誤消息。

我已經嘗試過使用onSubmit={() => getIngredient(id)}形式的值,然后它作為事件對象返回。 使用onSubmit={() => this.props.getIngredient(id)}它返回未定義的。 簡單地將其聲明為onSubmit={getIngredient(id)}也不起作用。

我已經對console.log進行了所有記錄,並且發現它在getIngredient(id)命中了dispatch操作時會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)```

這是因為在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>
  );
 }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM