繁体   English   中英

使用 react 调用 API 的最佳实践是什么

[英]What's the best practice to call API with react

在调用 API 时,我实际上在 React 中遇到了一个小问题,因为ComponentWillMount已被弃用。

我这样做了:

class MyClass extends Component {
  constructor() {
  super();

    this.state = {
      questionsAnswers: [[{ answers: [{ text: '', id: 0 }], title: '', id: 0 }]],

    },
  };
}
componentDidMount() {
   this.getQuestions();
}

getQuestions = async () => {
   let questionsAnswers = await Subscription.getQuestionsAndAnswers();
   questionsAnswers = questionsAnswers.data;
   this.setState({ questionsAnswers });
};

所以页面第一次呈现时没有questionsAsnwers ,当我得到questionAnswers页面被重新呈现

有没有更好的解决方案来避免重新渲染?

根据 react 文档,处理 API 调用的最佳方法是在componentDidMount方法 react lifeCycle 中。 此时您所能做的就是添加一个微调器,使您的组件更加用户友好。
希望在下一个 React 版本中。 React 将引入一种使用suspense方法解决此类问题的新方法https://medium.com/@baphemot/understanding-react-suspense-1c73b4b0b1e6

使用带有React.Component的类是componentDidMount

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };
  }

  componentDidMount() {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            items: result.items
          });
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

  render() {
    const { error, isLoaded, items } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <ul>
          {items.map(item => (
            <li key={item.id}>
              {item.name} {item.price}
            </li>
          ))}
        </ul>
      );
    }
  }
}

如果你在 Hooks 中使用函数组件,你应该这样做:

function MyComponent() {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);

  // Note: the empty deps array [] means
  // this useEffect will run once
  // similar to componentDidMount()
  useEffect(() => {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      )
  }, [])

  if (error) {
    return <div>Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div>Loading...</div>;
  } else {
    return (
      <ul>
        {items.map(item => (
          <li key={item.id}>
            {item.name} {item.price}
          </li>
        ))}
      </ul>
    );
  }
}

示例响应:

{
  "items": [
    { "id": 1, "name": "Apples",  "price": "$2" },
    { "id": 2, "name": "Peaches", "price": "$5" }
  ] 
}

来源:

https://reactjs.org/docs/faq-ajax.html

我认为,在这种情况下展示微调器是可以的。 您还应该检查 ajax 是否没有失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM