【问题标题】:handling mutliple inputs using redux使用 redux 处理多个输入
【发布时间】:2021-04-14 01:18:15
【问题描述】:

我有 react hooks 部分,用户可以在其中编辑输入字段,有数百个输入,这就是我需要使用 redux 的原因(虽然是新手到 redux),

codesandbox 现场演示:demo

到目前为止我有这个

const initialState = {
  firstName: "Kunta ",
  lastName: "Kinte"
};

const detailsReducer = (state = initialState, action) => {
  const { name, value } = action;

  return { ...state, [name]: value };
};

export default detailsReducer;

这里是在我有输入字段的地方设置 js

import React, { useState } from "react";
import { useSelector } from "react-redux";
import Details from "./Details";
import DetailsReducer from "../Reducer/DetailsReducer";

const Settings = () => {
  const fields = useSelector((state) => state.DetailsReducer);
  const [state, setState] = useState("");

  return (
    <div>
      <div>
        <h1>Edit </h1>
        <div className="container">
          <div className="inputs">
            <label htmlfor="fname">First name:</label>
            <input
              type="text"
              id="fname"
              name="fname"
              value={state}
              onChange={(e) => setState(e.target.value)}
            />
            <label htmlfor="lname" />
            Last name:
            <input type="text" id="lname" name="lname" onChange={(e) => setState(e.target.value)} />
          </div>
          <Details />
        </div>
      </div>
    </div>
  );
};

export default Settings;

预期结果:就在用户输入输入(例如名字)时,它应该更改详细信息组件中名字的值。

我正在努力让这个工作,有人可以帮忙吗?

【问题讨论】:

  • 我没有看到任何与使用 dispatch 更新 redux 状态相关的代码

标签: javascript reactjs redux state


【解决方案1】:

我 fork 你的 CodeSandbox 并得到了一个工作示例 here

关于我为使其正常工作所做的一些说明。

  1. 添加了redux 包,这是核心redux 功能。这就是让您创建 redux 存储的原因。查看文档here
  2. 使用redux 包中的createStore 创建storeDetailsReducer。查看此here
  3. 用来自react-reduxProvider 包裹App.js。这是你传递你的 redux store 的地方。检查文档here。这很重要,因为它是允许 React 应用程序与 redux 一起工作的集成。没有这个,你就不能使用useSelectoruseDispatch
  4. 下一部分是使用 redux 状态值并在您可以看到 here 的输入字段上调度。

需要明确的是,redux 包是核心 redux 功能。它是这样设计的,所以 redux 可以在任何地方使用(比如带有 NodeJS 的服务器端)。 react-redux 包是 react 集成,它使 react 应用程序使用 redux 变得容易。

旁注:从技术上讲,当您调用 dispatch 时,您传递一个 type 并且类型控制 reducer 如何更改其状态。您的示例非常简单,不需要类型,这就是为什么在示例中您将类型视为空字符串的原因。 Here 是在文档中使用 type 的示例。

【讨论】:

    猜你喜欢
    • 2021-12-07
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 2022-11-10
    • 2018-03-19
    相关资源
    最近更新 更多