【问题标题】:How to get Form submit value in react-redux with rails backend?如何在带有 Rails 后端的 react-redux 中获取表单提交值?
【发布时间】:2019-09-02 22:03:51
【问题描述】:

我有一个 Rails 后端,其中包含一个成分列表。我正在尝试使用搜索栏(表单)输入成分 ID 以查找合适的成分。 当我单击表单的提交按钮时,我想要以 ID 作为参数的调度函数 getIngredient,但是使用我尝试过的方法,我没有得到应该是 ID;它是未定义的,或者只是“一个事件”。我只是简单地看到了错误消息,所以我没有更多的细节。它只是刷新状态,删除错误消息。

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

我已经 console.logged 一切,我发现它在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)```

【问题讨论】:

    标签: javascript forms react-redux action dispatch


    【解决方案1】:

    这是因为在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>
      );
     }
    }
    
    

    【讨论】:

    • 嘿穆斯塔法!我正在使用 redux,所以它正在处理状态。即便如此,我还是尝试了你的代码:但是它给了我一个Uncaught ReferenceError: handleInputChange is not defined。我试着把它变成一个函数和一个常量,但同样的错误仍然存​​在。
    • @DavidBell 对不起,这是我的一个错误,应该是 this.handleInputChange 我编辑了代码,顺便说一句,因为您使用的是 redux 并不意味着您不应该使用 React 状态,您可以将它们组合在一起,例如为简单的 UI 状态创建 React 状态,为整个应用程序数据创建 redux
    • 所以它没有给我任何错误,它只是刷新。我安装了开发工具,当我在字段中键入时,我可以看到 onChange 更改了状态,但是按下按钮只会更新字段并擦除开发工具中没有任何痕迹的所有内容。我可以把getIngredient函数看成一个prop:{ "ingredients": [], "getIngredient": "fn()" }明天我会分离formReducer,并使用combineReducers让一切更标准,我会回报!
    • @DavidBell 我知道是什么原因造成的,因为提交事件的默认行为会再次编辑代码并防止这种默认行为发生
    • ID 已正确传送到 getIngredient 方法,谢谢。 Redux/React 的关系让我很困惑。我希望我的 getIngredient 方法有效,但这是另一个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    相关资源
    最近更新 更多