簡體   English   中英

如何在 React 的 return 語句中使用 fetch 結果?

[英]How to use fetch result in return statement in React?

我有一個顯示以下結果的獲取。 現在我想在 return 語句中顯示 fetch(在 div 結果中)。 有誰知道如何做到這一點。 我用 map function 嘗試了它,因為我雖然 fetch 是一個數組,但我失敗了。

 (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] 0: {label: "Hello world", href: "#hello-world"} 1: {label: "John Doe", href: "#john-doe"} 2: {label: "Jane Doe", href: "#jane-doe"} 3: {label: "Foo", href: "#foo"} 4: {label: "Bar", href: "#bar"} 5: {label: "Baz", href: "#baz"} 6: {label: "Henry Ford", href: "#henry-ford"} 7: {label: "Gordon Ramsay", href: "#gordon-ramsay"} 8: {label: "Angela Merkel", href: "#angele-merkel"} length: 9__proto__: Array(0)
 export function AutoSuggestForm({ onChange, value }) { React.useEffect(() => { const myFetch = fetch('http://localhost:8000/api/auto-suggest?input=input') myFetch.then(response => response.json()).then(console.log) }) return ( <div className={styles.component}> <input onChange={handleChange} {...{ value }} className={styles.input} type='search' placeholder='search' /> <div className={styles.results} /> </div> ) function handleChange(e) { onChange(e.target.value) } }

https://reactjs.org/docs/hooks-state.html

export function AutoSuggestForm({ onChange, value }) {
    const [data, setData] = React.useState([]);

    React.useEffect(() => {
        const myFetch = fetch('http://localhost:8000/api/auto-suggest?input=input');
        myFetch.then(response => response.json()).then(setData);
    });

    return (
        <div className={styles.component}>
            <input onChange={handleChange} {...{ value }} className={styles.input} type="search" placeholder="search" />
            <div className={styles.results}>
                {data.map(d => (
                    <div key={d.label}>{d.label}</div>
                ))}
            </div>
        </div>
    );
    function handleChange(e) {
        onChange(e.target.value);
    }
}

通過 React.useState 創建 state,當你得到結果時改變它。 這是反應的基礎

export function AutoSuggestForm({ onChange, value }) {
  const [results, changeResults] = React.useState([])
  React.useEffect(() => {
    const myFetch = fetch('http://localhost:8000/api/auto-suggest?input=input')
    myFetch.then(response => response.json()).then(res => changeResults(res))
  })
  return (
    <div className={styles.component}>
      <input onChange={handleChange} {...{ value }} className={styles.input} type='search' placeholder='search' />
      <div className={styles.results} >
        {results.map((result, i) => <span key={i}>{result}</span>}
      </div>
    </div>
  )
  function handleChange(e) {
    onChange(e.target.value)
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM