我如何使用钩子重写带有setState和回调的react-method?

问题描述 投票:0回答:2

我有一个react组件,它包含一个带有回调的setState方法。我需要用hooks重写它。请告诉我如何重写这个方法?

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

reactjs callback react-hooks setstate use-effect
2个回答
0
投票

你需要使用effect来实现这个功能。

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

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

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

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])
© www.soinside.com 2019 - 2024. All rights reserved.