反应:道具在反应中没有正确传递



我试图从服务器传回response消息并将其显示在UI中,但似乎每当我在第二个<Dialog>中传递response时,响应都是未定义的,我认为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={() => {}}
/>
)
}

对话框.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>
)
}
)
}

我认为您应该重构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>
};

相关内容

  • 没有找到相关文章

最新更新