Rect Hook通过useEffect处理http请求的演进

前言

最近开始学习React,跟着Kent学,有很多干货,这里具体分享一个通过useEffect处理异步http请求的方法,及其改进

我把代码放在了codesandbox上, 里面是一个fetch pokemon的场景,接下来会通过这个场景一步步介绍异步请求在React的使用


一、实现

1.0 基本方法

简单的处理方式就是如果需要发送HTTP请求,使用useEffect,然后通过.then()方法处理传过来的数据

React.useEffect(()=>{
	fetch(path).then(data=>{
		setData(data)
	})
}, [])

那么,运用到pokemon的场景就是当用户输入名字,PokemonInfo组件会获取名字,并发送http请求获取数据

  1. 没有输入名字的时候,提示用户输入
  2. 输入名字,但是还没有收到http response的时候,展示PokemonInfoFallback组件
  3. 收到了数据,展示PokemonDataView组件
function PokemonInfo({ pokemonName }) {
  const [pokemon, setPokemon] = React.useState(null);

  React.useEffect(() => {
    if (pokemonName === "") {
      return;
    }
    fetchPokemon(pokemonName).then((pokemonData) => {
      setPokemon(pokemonData);
    });
  }, [pokemonName]);

  if (!pokemonName) {
    return "Submit a pokemon";
  } else if (!pokemon) {
    return <PokemonInfoFallback name={pokemonName} />;
  } else {
    return <PokemonDataView pokemon={pokemon} />;
  }
}

1.1 添加错误处理

http可能会返回error,所以异步请求需要多error进行处理,方法也是比较简单的,就是添加一个error的state,每次请求setError为null,一旦请求catch到error,setError(error)

function PokemonInfo({ pokemonName }) {
  const [pokemon, setPokemon] = React.useState(null);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    if (pokemonName === "") {
      return;
    }
    setPokemon(null);
    setError(null);
    fetchPokemon(pokemonName)
      .then((pokemonData) => {
        setPokemon(pokemonData);
      })
      .catch(setError);
  }, [pokemonName]);

  if (!pokemonName) {
    return "Submit a pokemon";
  } else if (!pokemon) {
    return <PokemonInfoFallback name={pokemonName} />;
  } else if (error !== null) {
    return errorDiv(error);
  } else {
    return <PokemonDataView pokemon={pokemon} />;
  }
}

1.2 添加status

前面的例子中,判断的条件是很容易出错的

 if (!pokemonName) {
    return "Submit a pokemon";
  } else if (!pokemon) {
    return <PokemonInfoFallback name={pokemonName} />;
  } else if (error !== null) {
    return errorDiv(error);
  } else {
    return <PokemonDataView pokemon={pokemon} />;
  }

其实对于http请求来说有更加优雅的处理方式,那就是使用状态

idle: no request made yet
pending: request started
resolved: request successful
rejected: request failed

于是,可以写成这样

function PokemonInfo({ pokemonName }) {
  const [status, setStatus] = React.useState("idle");
  const [pokemon, setPokemon] = React.useState(null);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    if (pokemonName === "") {
      return;
    }
    setPokemon(null);
    setError(null);
    setStatus("pending");
    fetchPokemon(pokemonName)
      .then((pokemonData) => {
        setPokemon(pokemonData);
        setStatus("resolved");
      })
      .catch((error) => {
        setStatus("rejected");
        setError(error);
      });
  }, [pokemonName]);

  if (status === "idle") {
    return "Submit a pokemon";
  } else if (status === "pending") {
    return <PokemonInfoFallback name={pokemonName} />;
  } else if (status === "error") {
    return errorDiv(error);
  } else if (status === "resolved") {
    return <PokemonDataView pokemon={pokemon} />;
  }
}

1.3 使用object统一管理多个states

上面一共有三个states,每次都要非常小心的setState,而且比较大的问题是,setState的顺序会影响正确性,比如setPokemon一定需要放在setStatus之前,否则会报错,于是引入object统一管理

function PokemonInfo({ pokemonName }) {
  const [state, setState] = React.useState({
    status: "idle",
    pokemon: null,
    error: null
  });
  const { status, pokemon, error } = state;

  React.useEffect(() => {
    if (pokemonName === "") {
      return;
    }
    setState({ status: "pending" });
    fetchPokemon(pokemonName)
      .then((pokemonData) => {
        setState({
          status: "resolved",
          pokemon: pokemonData
        });
      })
      .catch((error) => {
        setState({
          status: "error",
          error
        });
      });
  }, [pokemonName]);

  if (status === "idle") {
    return "Submit a pokemon";
  } else if (status === "pending") {
    return <PokemonInfoFallback name={pokemonName} />;
  } else if (status === "error") {
    return errorDiv(error);
  } else if (status === "resolved") {
    return <PokemonDataView pokemon={pokemon} />;
  }
}

二、进阶 - 使用ErrorBoundary

有些时候,runtime error并不会被catch到,比如pokemonData返回的是null,回导致整个页面出错,这时候就需要ErrorBoundary 处理

首先实现一个ErrorBoundary的类,注意必须实现getDerivedStateFromError方法

import * as React from "react";

class ErrorBoundary extends React.Component {
  state = { error: null };
  static getDerivedStateFromError(error) {
    return { error };
  }
  render() {
    const { error } = this.state;
    if (error) {
      return <this.props.FallbackComponent error={error} />;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

然后就可以引入ErrorBoundary到App中, 注意需要把key传入ErrorBoundary,否则不能Re-mount

import "./styles.css";

// useEffect: HTTP requests
import * as React from "react";

import {
  PokemonForm,
  PokemonInfoFallback,
  PokemonDataView,
  fetchPokemon
} from "./pokemon";

import ErrorBoundary from "./ErrorBoundary";

function PokemonInfo({ pokemonName }) {
  const [state, setState] = React.useState({
    status: "idle",
    pokemon: null,
    error: null
  });
  const { status, pokemon, error } = state;

  React.useEffect(() => {
    if (pokemonName === "") {
      return;
    }
    setState({ status: "pending" });
    fetchPokemon(pokemonName)
      .then((pokemonData) => {
        setState({
          status: "resolved",
          pokemon: pokemonData
        });
      })
      .catch((error) => {
        setState({
          status: "error",
          error
        });
      });
  }, [pokemonName]);

  if (status === "idle") {
    return "Submit a pokemon";
  } else if (status === "pending") {
    return <PokemonInfoFallback name={pokemonName} />;
  } else if (status === "error") {
    throw error;
  } else if (status === "resolved") {
    return <PokemonDataView pokemon={pokemon} />;
  }
}

function ErrorFallback({ error }) {
  return (
    <div role="alert">
      There was an error:{" "}
      <pre style={{ whiteSpace: "normal" }}>{error.message}</pre>
    </div>
  );
}

function App() {
  const [pokemonName, setPokemonName] = React.useState("");

  function handleSubmit(newPokemonName) {
    setPokemonName(newPokemonName);
  }

  return (
    <div className="pokemon-info-app">
      <PokemonForm pokemonName={pokemonName} onSubmit={handleSubmit} />
      <hr />
      <div className="pokemon-info">
        <ErrorBoundary key={pokemonName} FallbackComponent={ErrorFallback}>
          <PokemonInfo pokemonName={pokemonName} />
        </ErrorBoundary>
      </div>
    </div>
  );
}

export default App;


总结

这里讲了基础的http处理的方法,可以通过status优雅的对不同转态render不同组件的需求,并且引入了ErrorBoundary处理run time error

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值