如何在反应钩子中监听 redux 状态的变化?

时间:2021-04-19 16:16:32

标签: javascript reactjs input redux react-redux

我有多个用户可以编辑的表单和按钮,如果 redux 的状态发生变化,我想显示一个按钮保存。

现场演示:display button save when the state changes

这是我的 redux。

const initialState = {
  firstName: "Kunta ",
  lastName: "Kinte",
  age: 35,
  country: "Ghana",
  color: "#000"
};

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

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

export default DetailsReducer;

这是我的 js 代码,用于在 redux 状态发生变化时显示保存按钮

    import React, { useState, useEffect } from "react";
    import { useSelector, useDispatch } from "react-redux";
    
    const Settings = () => {
      const fields = useSelector((state) => state);
      const dispatch = useDispatch();
      const [saveBtn, setSaveBtn] = useState(false);
    
      useEffect(() => {
        setSaveBtn(true); // show save btn if there is changes in state
      }, []);
    
      console.log(fields.firstName);
    
      return (
        <div>
          <div>
            <h1>Edit </h1>
            First Name:{" "}
            <input
              name="firstname"
              value={fields.firstName}
              onChange={(e) =>
                dispatch({ name: "firstName", value: e.target.value, type: "" })
              }
            />
            {saveBtn === true && <button className="btn-save">save </button>}
          </div>
        </div>
      );
    };
    
    export default Settings;


  [1]: https://codesandbox.io/s/multiple-inputs-kkm6l?file=/src/Components/Settings.js:0-816

我需要做什么来解决这个问题。?

2 个答案:

答案 0 :(得分:1)

你可以试试这样的:

<input
    name="firstname"
    value={fields.firstName}
    onChange={(e) =>
        dispatch({ name: "firstName", value: e.target.value, type: "" }, setSaveBtn(true))
    }
/>

同时删除:

useEffect(() => {
    setSaveBtn(true); // show save btn if there is changes in state
}, []);

答案 1 :(得分:0)

你可以这样做。去掉效果钩子,移动setSaveBtn输入onChange,点击save后,设置setSaveBtn为false。

    import React, { useState, useEffect } from "react";
    import { useSelector, useDispatch } from "react-redux";
    
    const Settings = () => {
      const fields = useSelector((state) => state);
      const dispatch = useDispatch();
      const [saveBtn, setSaveBtn] = useState(false);
    
      console.log(fields.firstName);
    
      return (
        <div>
          <div>
            <h1>Edit </h1>
            First Name:{" "}
            <input
              name="firstname"
              value={fields.firstName}
              onChange={(e) => {
                dispatch({ name: "firstName", value: e.target.value, type: "" })
                setSaveBtn(true)
              }}
            />
            {saveBtn === true && 
              <button
               onClick={() => setSaveBtn(false)}
              className="btn-save">save </button>}
          </div>
        </div>
      );
    };
    
    export default Settings;