簡體   English   中英

如何清除useState? 反應鈎子

[英]How to clear useState? React hook

我想清除 useState 但沒有用。 他每次都記得我的老state。 我使用傳播運算符。 檢查我的代碼:

  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

也沒有工作。

他記得每一個下一個值。 我希望它完全刪除我在 function 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)
);

你可以寫一個React.useEffect鈎子,你可以像下面這樣寫一個清理 function

React.useEffect(()=>{
# here is your cleanup function where you can reset states
  return () => {
    setSelectedUnits([]);  
    onCancel(); 
    clearStoreDataAfterCancel();
  }
},[])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM