React Toastify - 没有收到错误通知

React Toastify - Not getting error notification

我想要的是,当我没有从 api 获得任何数据时,而不是这个没有数据,我想要一个通知或 toast.error 来显示。

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;

在第 6 行你可以看到 <span >No data</span> 而不是这个我想要一个 toast.error 通知,但是当我写 toast.error("No data"); 而不是这个跨度时,我得到了这样的东西而不是错误通知

如果你想祝酒数组为空时没有数据,需要分两步完成,因为render是一个纯函数,即没有副作用

  1. 在组件生命周期函数中发布toastside-effect,即componentDidMountand/orcomponentDidUpdate
  2. 在没有数据烘烤时呈现 null,或者由于地图可以毫无问题地处理空数组,只需 return 空地图结果数组

代码

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>
    );
  }
}