我如何在我的 Api 服务中呈现 A 模态?
How can i render A modal in my Api servises?
你好,当我的 api 响应出错时,我试图每次都显示一个模态,你能帮我吗?我该怎么做 ?我正在使用反应钩子
const restService = (path, responseType = 'json') => {
const apiUrl = `${CONFIG.API_HOST}/${path}`;
const create = async (body) => {
const config = {
responseType
};
try {
const response = await axios.post(apiUrl, body, config);
return response.data;
} catch (errors) {
//show modal
return {errors};
}
};
return {
find,
create,
update,
remove
};
};
模态和激活模态的设置
Modal
settings if modal is showing or not
您可以使用 React's Conditional Rendering 来实现。
这里有一个关于如何实现这一点的例子:https://dev.to/kevhines/triggering-an-error-modal-in-react-3pm9
文章末尾的错误消息组件如下所示:
import React from "react";
import {connect} from 'react-redux'
import clearError from '../actions/clearError'
class ErrorModal extends React.Component {
state = {
show: false
};
onClick = (e) => {
this.setState({
show: false
});
this.props.clearError()
};
componentDidUpdate(prevProps) {
if (this.props.error && !prevProps.error) {
this.setState({
show: true
});
}
}
render() {
if(!this.state.show){
return null;
}
return <div className="modal" id="modal">
<div>
<a href="#close" title="Close" className="close" onClick={this.onClick}>X</a>
<h2>Error Message</h2>
<p>{this.props.error}</p>
</div>
</div>
}
}
function mapStateToProps(state) {
return {error: state.error}
}
export default connect(mapStateToProps, {clearError})(ErrorModal)
你好,当我的 api 响应出错时,我试图每次都显示一个模态,你能帮我吗?我该怎么做 ?我正在使用反应钩子
const restService = (path, responseType = 'json') => {
const apiUrl = `${CONFIG.API_HOST}/${path}`;
const create = async (body) => {
const config = {
responseType
};
try {
const response = await axios.post(apiUrl, body, config);
return response.data;
} catch (errors) {
//show modal
return {errors};
}
};
return {
find,
create,
update,
remove
};
};
模态和激活模态的设置
Modal
settings if modal is showing or not
您可以使用 React's Conditional Rendering 来实现。
这里有一个关于如何实现这一点的例子:https://dev.to/kevhines/triggering-an-error-modal-in-react-3pm9
文章末尾的错误消息组件如下所示:
import React from "react";
import {connect} from 'react-redux'
import clearError from '../actions/clearError'
class ErrorModal extends React.Component {
state = {
show: false
};
onClick = (e) => {
this.setState({
show: false
});
this.props.clearError()
};
componentDidUpdate(prevProps) {
if (this.props.error && !prevProps.error) {
this.setState({
show: true
});
}
}
render() {
if(!this.state.show){
return null;
}
return <div className="modal" id="modal">
<div>
<a href="#close" title="Close" className="close" onClick={this.onClick}>X</a>
<h2>Error Message</h2>
<p>{this.props.error}</p>
</div>
</div>
}
}
function mapStateToProps(state) {
return {error: state.error}
}
export default connect(mapStateToProps, {clearError})(ErrorModal)