如何解决如何在Reactjs中组织异步获取代码
在许多组件中,我需要获取一些数据,最后得到许多类似的代码。看起来像这样:
class Example()(implicit system: ActorSystem,materializer: ActorMaterializer)
如何将其放入库中并重复使用?
解决方法
您可以将API调用包装在ipmax
文件夹中,并在任何地方使用
%%b
示例
Auth.js
/services
在您的组件中
/services
- Auth.js
- Products.js
- etc...
,
谢谢你们的建议,我提出了以下建议。对于一些批评家会很高兴。
function useFetch(id,setData) {
const [fetchingState,setFetchingState] = useState(FetchingState.Idle);
useEffect(() => { loadDataFromServer(id); },[id]);
async function loadDataFromServer(id) {
let url = new URL(`${process.env.REACT_APP_API}/data/${id}`);
let timeout = setTimeout(() => setFetchingState(FetchingState.Loading),1000)
try {
const result = await axios.get(url);
setData(result.data);
setFetchingState(FetchingState.Idle);
}
catch (error) {
setData();
setFetchingState(FetchingState.Error);
}
clearTimeout(timeout);
}
return fetchingState;
}
这就是我的用法:
function Thread(props) {
const [question,setQuestion] = useState();
const fetchingState = useFetch(props.questionId,setQuestion);
if (fetchingState === FetchingState.Error) return <p>Error while getting the post.</p>;
if (fetchingState === FetchingState.Loading) return <Spinner />;
return <div>{JSON.stringify(question)}</div>;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。