reactjs - React Toastify - Not getting error notification
问题描述
What I want is, when I get no data from the api, instead of this No data, I want A notification or toast.error to get displayed.
shops.jsx
import React from 'react';
import './shops.css';
import Shop from './shop'
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
require('dotenv').config()
const TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1ZjFiMjNlYTQxNmJhMjQ3YjQ5MDk4Y2IiLCJlbWFpbCI6Img1aW1icjQ0NGQ7QHR5cC5pbiIsImlhdCI6MTU5NjgxMTU5MSwiZXhwIjoxNTk2ODE1MTkxfQ.UyrUkbNWzenf50FL8AZE1iZaii11P7MwdXpKmoCB9nM";
class Shops extends React.Component {
constructor(props) {
super(props);
this.state = {
shops: []
};
}
componentDidMount() {
console.log(process.env.REACT_APP_BaseURL);
// replace with correct URL: http://localhost:5000/api/shops/allShops
fetch(process.env.REACT_APP_BaseURL, {
method: "get",
headers: new Headers({
Authorization: `Bearer ${TOKEN}`
})
})
.then(response =>response.json())
.then(data => {
this.setState({ shops: data.fetchedShops });
toast.success("API LOADED SUCCESSFULLY","SUCCESS");
})
.catch(err =>{
console.log("Error", err);
if(err){
toast.error("error occured");
}
});
}
render() {
const shops =
this.state.shops.length > 0 ?
this.state.shops.map(item => (
<Shop name={item.shopname} address={item.address} mobile={item.phoneNumber} />
))
: <span >No data</span>;
console.log(this.state.shops);
return <div id="container">{shops}</div>;
}
}
export default Shops;
In the 6th line you can see <span >No data</span>
instead of this I want a toast.error notification, but when I write toast.error("No data");
instead of this span i got something like this instead of error notification
解决方案
If you want to toast that there is no data when the array is empty it needs to be done in two steps since render
is a pure function, i.e. without side effects
- Issue toast side-effect in component lifecycle functions, i.e.
componentDidMount
and/orcomponentDidUpdate
- Render
null
when toasting no data, or since the map can handle empty arrays without issue, just return the empty map result array
Code
class Shops extends Component {
state = {
shops: []
};
checkShops = () => {
const { shops } = this.state;
if (!shops.length) {
toast.error("No Data");
}
};
componentDidMount() {
this.checkShops(); // not really needed if fetch for data first
}
componentDidUpdate() {
this.checkShops();
}
render() {
const { shops } = this.state;
return (
<div id="container">
{shops.map((item) => <div>Data</div>)}
</div>
);
}
}
推荐阅读
- typescript - 打字稿:带有可选参数的重载:“重载签名与函数实现不兼容。”
- python - 如何使用后台作业在 Django 中使用消息框架显示消息?
- java - Android 9.0 Pie 的毕加索图像加载问题
- c - 用户输入的错误处理,直到输入正确
- javascript - JavaScript 确认框上的取消选项仅返回真条件
- android - 位图 - 避免在缩放期间在内存中进行不必要的加载
- emacs - 将转义序列从 tmux 传递到 gnu 屏幕
- c - 使用strtod后如何将double值转换为char数组?在 C 中
- sonata - 奏鸣曲分类捆绑路径问题
- python-3.x - 模仿操作系统调度程序的协程