[英]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.