如何清除useState?反应钩子
我想清除 useState 但没有工作。他每次都记得我以前的状态。我使用扩展运算符。检查我的代码:
const [selectedUnits, setSelectedUnits] = useState([]);
const handleChange = (value) => {
setSelectedUnits((state) => [...state, value]);
dispatch(
getSelectedOrganisationUnits({
selectedOrganisationUnit: [...selectedUnits, value]
})
);
};
这部分代码我合并了两个值 ->
setSelectedUnits((state) => [...state, value]);
当我关闭模式时 ->
const closeModal = useCallback(() => {
console.log("clear called!");
setSelectedUnits([]); // NOT CLEAR ME ALL VALUE!
onCancel();
}, [onCancel]);
上面的代码不起作用。我清除值->
setSelectedUnits([]);
但没有工作。
我也尝试过->
const closeModal = useCallback(() => {
setSelectedUnits([]);
onCancel();
clearStoreDataAfterCancel();
}, [onCancel, selectedUnits]); // add selectedUnits
也没有工作。
他记住了每一个下一个值。我希望它完全消除我在函数 closeModal 中的值
更多显示商店 ->
export function getSelectedOrganisationUnits(data) {
return {
type: GET_SELECTED_ORGANISATION_UNITS,
payload: { data }
};
}
export function getNewOrganisationUnitName(data) {
return {
type: GET_NEW_ORGANISATION_UNIT_NAME,
payload: { data }
};
}
export function saveMergedOrganisation(data) {
return {
type: SAVE_MERGED_ORGANISATION,
payload: { data }
};
}
也来展示一下我的减速机->
const INITIAL_STATE = {
units: [],
flatUnits: [],
selectedUnits: [],
newOrganisationName: ""
};
export default function (state = INITIAL_STATE, action) {
switch (action.type) {
case GET_SELECTED_ORGANISATION_UNITS:
return {
...state,
selectedUnits: action.payload.data.selectedOrganisationUnit
};
case GET_NEW_ORGANISATION_UNIT_NAME:
return {
...state,
newOrganisationName: action.payload.data.newName
};
case SAVE_MERGED_ORGANISATION_SUCCESS:
return { ...state, units: action.payload.units };
default:
return state;
}
}
另外我想显示我选择值的下拉菜单 ->
<Col style={{ marginTop: "20px" }}>
<Field
id="firstUnit"
name="firstUnit"
component={renderStyledDropdown}
label={`${intl.formatMessage(messages.Unit)} 1`}
placeholder={intl.formatMessage(messages.selectFirstUnit)}
resetValue={null}
size="large"
clearable
options={flatUnits}
onChange={handleChange}
rounded
/>
<Field
id="secondUnit"
name="secondUnit"
component={renderStyledDropdown}
label={`${intl.formatMessage(messages.Unit)} 2`}
placeholder={intl.formatMessage(messages.selectSecondUnit)}
resetValue={null}
size="large"
clearable
options={flatUnits}
onChange={handleChange}
rounded
/>
</Col>
逻辑所在的所有组件 ->
const MergeUnitsModal = ({
intl,
show,
hide,
flatUnits,
title,
description,
submitButtonText,
preselectedItemsIds,
onCancel,
onSubmit,
primaryButtonTitle,
secondaryButtonTitle,
additionalFoooterContent,
onHide,
currentModal
}) => {
const [selectedUnits, setSelectedUnits] = useState([]);
const [value, setValue] = useState("");
let nameRef = useRef();
let { newOrganisationName, allSelectedUnits } = useSelector(
({ organisationStructure }) => {
newOrganisationName = organisationStructure.newOrganisationName;
allSelectedUnits = organisationStructure.selectedUnits;
return {
newOrganisationName,
allSelectedUnits
};
}
);
useEffect(() => {
// return () => {
setSelectedUnits([]);
console.log("test called");
// onCancel();
// clearStoreDataAfterCancel();
// };
}, [onCancel]);
const dispatch = useDispatch();
const closeModal = useCallback(() => {
console.log("on close called");
onCancel();
clearStoreDataAfterCancel();
}, [onCancel]);
const clearStoreDataAfterCancel = () => {
console.log("a");
setTimeout(() => {
setSelectedUnits([]);
dispatch(
getSelectedOrganisationUnits({
selectedOrganisationUnit: []
})
);
dispatch(
getNewOrganisationUnitName({
newName: ""
})
);
}, 500);
};
const handleChange = (value) => {
// setSelectedUnits((prevState) => [...prevState, value]);
// setSelectedUnits((prevState) => console.log("prevState", prevState));
// nameRef(...value);
nameRef.current = value;
console.log("nameRef", nameRef);
dispatch(
getSelectedOrganisationUnits({
selectedOrganisationUnit: [...nameRef, value]
})
);
};
const handleChangeName = (e) => {
setValue(e.target.value);
dispatch(
getNewOrganisationUnitName({
newName: e.target.value
})
);
};
const renderPageContent = (content) => {
switch (content) {
case "showFirstModal":
return (
<FirstPageContent
flatUnits={flatUnits}
handleChange={handleChange}
description={description}
/>
);
case "showSecondModal":
return <SecondPageContent handleChangeName={handleChangeName} />;
case "showThirdModal":
return <ThirdPageContent />;
default:
break;
}
};
return (
<Modal
show={show}
onHide={onHide}
width={currentModal === "showThirdModal" ? "450px" : "500px"}
simpleModal={currentModal === "showThirdModal" ? true : false}
additionalFoooterContent={additionalFoooterContent}
customButtons={[
<ButtonContainer>
<Button
title={intl.formatMessage(messages.cancel)}
transparent
id="cancel"
onClick={closeModal}
style={{ marginRight: 10 }}
/>
<Button
title={primaryButtonTitle}
id="add"
type="submit"
onClick={onSubmit}
disabled={
(currentModal === "showFirstModal" &&
allSelectedUnits?.length < 2) ||
(currentModal === "showSecondModal" &&
newOrganisationName?.length < 1)
}
/>
</ButtonContainer>
]}
center="true"
title={intl.formatMessage(messages.mergeOrganisationUnits)}
>
{renderPageContent(currentModal)}
</Modal>
);
};
export default injectIntl(
reduxForm({
form: "mergeUnits"
})(MergeUnitsModal)
);
I want to clear useState but no work. He remembers my old state every time. I use a spread operator. Check my code:
const [selectedUnits, setSelectedUnits] = useState([]);
const handleChange = (value) => {
setSelectedUnits((state) => [...state, value]);
dispatch(
getSelectedOrganisationUnits({
selectedOrganisationUnit: [...selectedUnits, value]
})
);
};
this part of code I merge two value ->
setSelectedUnits((state) => [...state, value]);
When I close my modal ->
const closeModal = useCallback(() => {
console.log("clear called!");
setSelectedUnits([]); // NOT CLEAR ME ALL VALUE!
onCancel();
}, [onCancel]);
Code above no work. I clear value ->
setSelectedUnits([]);
But no work.
What I try also ->
const closeModal = useCallback(() => {
setSelectedUnits([]);
onCancel();
clearStoreDataAfterCancel();
}, [onCancel, selectedUnits]); // add selectedUnits
Also no work.
He remembers every next value. I want it to completely erase my value in function closeModal
More to show store ->
export function getSelectedOrganisationUnits(data) {
return {
type: GET_SELECTED_ORGANISATION_UNITS,
payload: { data }
};
}
export function getNewOrganisationUnitName(data) {
return {
type: GET_NEW_ORGANISATION_UNIT_NAME,
payload: { data }
};
}
export function saveMergedOrganisation(data) {
return {
type: SAVE_MERGED_ORGANISATION,
payload: { data }
};
}
Also to show my reducer ->
const INITIAL_STATE = {
units: [],
flatUnits: [],
selectedUnits: [],
newOrganisationName: ""
};
export default function (state = INITIAL_STATE, action) {
switch (action.type) {
case GET_SELECTED_ORGANISATION_UNITS:
return {
...state,
selectedUnits: action.payload.data.selectedOrganisationUnit
};
case GET_NEW_ORGANISATION_UNIT_NAME:
return {
...state,
newOrganisationName: action.payload.data.newName
};
case SAVE_MERGED_ORGANISATION_SUCCESS:
return { ...state, units: action.payload.units };
default:
return state;
}
}
Also I want to show my dropdown where i choose values ->
<Col style={{ marginTop: "20px" }}>
<Field
id="firstUnit"
name="firstUnit"
component={renderStyledDropdown}
label={`${intl.formatMessage(messages.Unit)} 1`}
placeholder={intl.formatMessage(messages.selectFirstUnit)}
resetValue={null}
size="large"
clearable
options={flatUnits}
onChange={handleChange}
rounded
/>
<Field
id="secondUnit"
name="secondUnit"
component={renderStyledDropdown}
label={`${intl.formatMessage(messages.Unit)} 2`}
placeholder={intl.formatMessage(messages.selectSecondUnit)}
resetValue={null}
size="large"
clearable
options={flatUnits}
onChange={handleChange}
rounded
/>
</Col>
And all component where is logic ->
const MergeUnitsModal = ({
intl,
show,
hide,
flatUnits,
title,
description,
submitButtonText,
preselectedItemsIds,
onCancel,
onSubmit,
primaryButtonTitle,
secondaryButtonTitle,
additionalFoooterContent,
onHide,
currentModal
}) => {
const [selectedUnits, setSelectedUnits] = useState([]);
const [value, setValue] = useState("");
let nameRef = useRef();
let { newOrganisationName, allSelectedUnits } = useSelector(
({ organisationStructure }) => {
newOrganisationName = organisationStructure.newOrganisationName;
allSelectedUnits = organisationStructure.selectedUnits;
return {
newOrganisationName,
allSelectedUnits
};
}
);
useEffect(() => {
// return () => {
setSelectedUnits([]);
console.log("test called");
// onCancel();
// clearStoreDataAfterCancel();
// };
}, [onCancel]);
const dispatch = useDispatch();
const closeModal = useCallback(() => {
console.log("on close called");
onCancel();
clearStoreDataAfterCancel();
}, [onCancel]);
const clearStoreDataAfterCancel = () => {
console.log("a");
setTimeout(() => {
setSelectedUnits([]);
dispatch(
getSelectedOrganisationUnits({
selectedOrganisationUnit: []
})
);
dispatch(
getNewOrganisationUnitName({
newName: ""
})
);
}, 500);
};
const handleChange = (value) => {
// setSelectedUnits((prevState) => [...prevState, value]);
// setSelectedUnits((prevState) => console.log("prevState", prevState));
// nameRef(...value);
nameRef.current = value;
console.log("nameRef", nameRef);
dispatch(
getSelectedOrganisationUnits({
selectedOrganisationUnit: [...nameRef, value]
})
);
};
const handleChangeName = (e) => {
setValue(e.target.value);
dispatch(
getNewOrganisationUnitName({
newName: e.target.value
})
);
};
const renderPageContent = (content) => {
switch (content) {
case "showFirstModal":
return (
<FirstPageContent
flatUnits={flatUnits}
handleChange={handleChange}
description={description}
/>
);
case "showSecondModal":
return <SecondPageContent handleChangeName={handleChangeName} />;
case "showThirdModal":
return <ThirdPageContent />;
default:
break;
}
};
return (
<Modal
show={show}
onHide={onHide}
width={currentModal === "showThirdModal" ? "450px" : "500px"}
simpleModal={currentModal === "showThirdModal" ? true : false}
additionalFoooterContent={additionalFoooterContent}
customButtons={[
<ButtonContainer>
<Button
title={intl.formatMessage(messages.cancel)}
transparent
id="cancel"
onClick={closeModal}
style={{ marginRight: 10 }}
/>
<Button
title={primaryButtonTitle}
id="add"
type="submit"
onClick={onSubmit}
disabled={
(currentModal === "showFirstModal" &&
allSelectedUnits?.length < 2) ||
(currentModal === "showSecondModal" &&
newOrganisationName?.length < 1)
}
/>
</ButtonContainer>
]}
center="true"
title={intl.formatMessage(messages.mergeOrganisationUnits)}
>
{renderPageContent(currentModal)}
</Modal>
);
};
export default injectIntl(
reduxForm({
form: "mergeUnits"
})(MergeUnitsModal)
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以编写一个
React.useEffect
钩子,并在其中编写一个清理函数,如下所示You can write a
React.useEffect
hook and with in that you can write a cleanup function like bellow