如何在react钩子中监听redux状态的变化



我有多个表单和按钮,用户现在可以编辑它们。如果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

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

你试过这个吗?

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

您可以尝试以下操作:

<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
}, []);

您可以这样做。移除效果挂钩,将setSaveBtn移动到onChange输入,单击保存后,只需将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;

相关内容

  • 没有找到相关文章

最新更新