从React JS中的api请求中获取第一个值



在我的react js应用程序中,我使用react select=>图书馆https://react-select.com/home#getting-已启动

import "./styles.css";
import Select from 'react-select'
import { useState, useEffect } from "react";
export default function App() {
const [state, setState] = useState();

useEffect(() => {
const response = fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(json => setState(json?.map((i) => {
return {label: i.name, value: i.name}
})))
},[])
console.log(state?.[0])
return (
<div className="App">
<Select
defaultValue={state?.[0]} //expect the first value that comes from back-end
options={state} 
/> 
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}

您可以注意到,我将来自apidefaultValue={state?.[0]}的第一个值设置为初始值,但该值不会显示为默认值,即使在console.log中也会显示。我假设发生这种情况是因为第一次渲染时的undefined值,所以在第一次渲染中,state?.[0]是未定义的,但之后该值将显示在控制台中。如何获取select中的初始值
演示:https://codesandbox.io/s/hopeful-keldysh-6xynq?file=/src/App.js:0-705

useEffect在第一次渲染后调用API是正确的。对于大多数情况,这是一件好事,因为它允许您在等待API调用完成时呈现内容,例如加载微调器:

export default function App() {
const [state, setState] = useState();

useEffect(() => {
const response = fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(json => setState(json?.map((i) => {
return {label: i.name, value: i.name}
})))
},[])
if (!state) {
// you can display a loading spinner here if you want
return null;
}
// Once we've reached this point on subsequent renders, state should be defined
return (
<div className="App">
<Select
defaultValue={state.[0]} //expect the first value that comes from back-end
options={state} 
/> 
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}

还要注意的是,因为您使用的是defaultValue,所以在最初渲染/安装Select组件时必须有状态定义,因为您发送到defaultValue的后续更改不会影响当前值(因为该值已经"默认"为未定义(。

最新更新