我从后端获取一个数组或对象,我的任务是将第一个索引均值[0]设置为默认值,但当我设置时,我会得到未定义的值,您可以在代码中看到userL使用我的对象数组,但当打印username时,它会显示label:undefined value:undefine或当我打印userL时我正在获取我的对象列表数组
const [userL, setUserL] = useState([]);
useEffect(() => {
axios
.get(`${DJANGO_SERVER_ADDRESS}/auth/analyst/`)
.then((res) => {
setUserL(res.data);
})
.then(
(result) => {
},
(error) => {
}
);
}, []);
console.log("ena1", userL);
const [userle, setUserle] = useState(
{ value: userL[0].username,
label: userL[0].username,
});
console.log("nnnnnnnnnuuuu",userle)
console.log('nnnnnnnnnnn',userL[0])
const handleSelectChangeL = (object, action) => {
setIndex(userL[object.id]);
setUserlevel(null);
console.log("select check", object.label, action.name, index);
let name = action.name;
let value = object.value;
setFormData((prevFormData) => ({
...prevFormData,
[name]: value,
}));
};
<Col lg={2}>
<label for="user">
<header>User</header>
</label>
<Select
options={userL.map((data, index) => ({
value: data.username,
label: data.username,
id: index,
}))}
styles={styles2}
value={userle}
name="user"
onChange={handleSelectChangeL}
placeholder="User"
theme={(theme) => ({
...theme,
colors: {
...theme.colors,
text: "black",
primary25: "#d6fdf7",
primary: "#0bb7a7",
primary50: "#d6fdf7",
},
})}
></Select>
</Col>
如果您想从数据的第一个元素设置userle的状态,可以这样做。
const [userle, setUserle] = useState()
const [userL, setUserL] = useState([]);
useEffect(() => {
axios
.get(`${DJANGO_SERVER_ADDRESS}/auth/analyst/`)
.then((res) => {
setUserL(res.data);
setUserle(res.data[0]?.username);
})
.then(
(result) => {
},
(error) => {
}
);
}, []);
编辑
要更新下拉列表的用户状态onChange,请在handleSelectChangeL
函数下添加setUserle()
。
JS
const handleSelectChangeL = (object, action) => {
setIndex(userL[object.id]);
setUserlevel(null);
console.log("select check", object.label, action.name, index);
let name = action.name;
let value = object.value;
setUserle(value); // Add this line
setFormData((prevFormData) => ({
...prevFormData,
[name]: value,
}));
};
如果您使用useState,您无法在同一函数中获得更新状态的预期结果,但如果要打印结果,您必须编写具有依赖项userle state的useEffect,或者您可以在上面控制台它"返回";功能组件中的语句