我该如何用钩子重写setState和callback的react-method?

时间:2020-05-14 08:39:18

标签: reactjs callback react-hooks setstate use-effect

我有一个react组件,其中包含带有setState和回调的方法。我需要将其重写为钩子。请告诉我如何重写此方法?

 beforeSubmitModal = action => (args) => {
    this.setState({
      visible: false,
      selectedMenuItem: null,
      companyCodeModal: {}
    }, () => action(args));
  };

const onDeleteCode = (id) => {
    dispatch(actions.deleteCode.request({ codeId: id }));
  };

const modalProps = {
    onSaveOrUpdate: beforeSubmitModal(dispatch(actions.insertOrEditCode.request())),
    onDelete: beforeSubmitModal(onDeleteCode),
  };

2 个答案:

答案 0 :(得分:0)

您将需要使用useEffect来完成

const [visible,setVisible] = useState(ture);

const doSomething = () => {
  setVisible(false);
}

useEffect(() => {
   //this will render every time the visible state changes
}, [visible]);

答案 1 :(得分:0)

定义挂钩中的状态

const [visible,setVisible]=useState(false) // initial value false
const [selectedMenuItem,setCompanyCodeModal]=useState(null) // initial value null
const [companyCodeModal,setCompanyCodeModal]=useState('') 

当他们改变时您需要采取一些行动

useEffect(()=> doSomething() ,[visible,selectedMenuItem,companyCodeModal])