We want to hear from you!Take our 2021 Community Survey!
אתר זה אינו מעודכן יותר.עבור אל react.dev

AJAX ו-APIs

איך אני יכול ליצור בקשת ?AJAX

אתה יכול להשתמש בכל ספריית AJAX שבחר עם React. כמה פופלאריות הן Axios, jQuery AJAX והמובנית בדפדפן window.fetch.

איפה במחזור החיים של הקומפוננטה אני צריך ליצור בקשת AJAX?

אתה צריך לאכלס נתונים ובקשות AJAX במתודה componentDidMount במחזור החיים. זה בשביל שתוכל להשתמש ב-setState כדי לעדכן את הקומפוננטה שלך מתי שהנתונים חוזרים.

דוגמא: שימוש כתוצאה מ-AJAX כדי להגדיר state מקומי

הקומפוננטה למטה מדגימה איך ליצור בקשת AJAX ב-componentDidMount לאכלס state מקומי בקומפוננטה.

דוגמת ה-API מחזירה אובייקט JSON כזה:

{
  "items": [
    { "id": 1, "name": "Apples",  "price": "$2" },
    { "id": 2, "name": "Peaches", "price": "$5" }
  ] 
}
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
          });
        },
        // שים לב: חשוב לטפל בשגיאות כאן
        // כדי שלא נפספס catch()-במקום הבלוק
        // על מנת שלא "נבלע" חריגות מבאגים בקומפוננטות שלנו.
        (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>
      );
    }
  }
}

Here is the equivalent with 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>
    );
  }
}
האם התוכן בעמוד זה היה שימושי?לעריכת העמוד הנוכחי