React:道具在React中传递不正确

时间:2020-06-25 17:40:05

标签: javascript reactjs dom react-hooks

我试图将response消息从服务器传递回并显示在UI中,但是似乎每当我在第二个response中传递<Dialog>时,响应都是不确定的,我认为response仅在处理提交功能中定义。

有没有办法将response传递到<Dialog>

const AppNav = () => {
    //...
    const [popupOpen, setPopupOpen] = useState(false);
    const [secondPopupOpen, setSecondPopupOpen] = useState(false);
    const [input, setInput] = useState('');

const renderContent = () => { 
  return ( 
    <form>
     <input
      type="text"
      onChange={e => setInput(e.target.value)}
      value={input}
      onBlur={() =>delay(() =>setInput(''),150}
      placeholder='placeholder here...'
     />
    </form>
  );
};

const renderAction = () => { 
  const handleSubmit = async() => {
    //some server calls here
    //response is what got back from server call
  const response = await service.send(request)
  try{
    if(response.result ==='success'){
      setPopupOpen(false);
      setSecondPopupOpen(true);
     }else { throw new Error()}
    }
  catch (err) {throw new Error()}
  return response;
  }
  return ( 
    <Button onClick={handleSubmit}>Submit</Button>
  );
};
  //...
  return (
   <Button onClick={() => setPopupOpen(true)}>open button</Button>
   <Dialog
     open={popupOpen}
     renderContent={renderContent}
     renderAction={renderAction}
   />
   <Dialog
     open={secondPopupOpen}
     renderContent={(response) => <span><>{response.resultMessage}</span>}
     renderAction={() => {}}
   />
  )
}

Dialog.js

const Dialog = props => {
 const { renderAction, renderContent, renderTitle} = props;
 return (
  render={
   ({getTitleProps, getContentProps, getActionProps}) => (
     <DialogTitle {...getTitleProps()}>
      {renderTitle ? renderTitle() : <span>Title</span>}
     </DialogTitle>
     <DialogContent {...getContentProps()}>
      {renderContent ? renderContent() : <span>Content</span>}
     </DialogContent>
     <DialogAction {...getActionProps()}>
      {renderAction ? renderAction() : <span>Action</span>}
     </DialogAction>
   )
  }
 )
}

1 个答案:

答案 0 :(得分:1)

我认为您应该重构renderAction函数并将请求的状态以及错误(或将它们组合成一个状态)存储在某个地方。

const [response, setResponse] = useState(null);
const [error, setError] = useState(null);

const handleSubmit = async() => {
  const response = await service.send(request)
  try {
    if(response.result ==='success'){
      setPopupOpen(false);
      setSecondPopupOpen(true);
      setResponse(response);
      return;
    }

    setError(new Error('error'));
  }
  catch (error) {
    setError(error);
  }
}

const renderAction = () => {
  if(response) {
    return response;
  }

  if(error) {
    return error.message // to-do
  }

  return <Button onClick={handleSubmit}>Submit</Button>
};