【发布时间】:2021-06-17 07:45:16
【问题描述】:
我正在尝试为我的react-select 设置默认值,但它无法正常工作。
import Select from 'react-select';
我有所选属性的状态
const [ selectedProps, setSelectedProps ] = useState([]);
在我的 useEffect 中,我设置了来自道具的值
setSelectedProps(props.location.user.properties);
在渲染组件之前,我会记录数据以确保正确
console.log(properties);
console.log(selectedProps);
这是我的选择
<Select
defaultValue={selectedProps}
isMulti
name="properties"
options={properties}
className="basic-multi-select"
classNamePrefix="select"
onChange={handleChangeProperties}
/>
defaultValue 没有显示任何内容。
日志,起初properties 和selectedProps 都是空的。然后,它具有值的第二个日志:
属性:
[
(3) […]
0: Object { value: 2618, label: "Prop 1" }
1: Object { value: 2309, label: "Prop 2" }
2: Object { value: 2192, label: "Prop 3" }
length: 3
<prototype>: Array []
selectedProps:
[
{
"value": 2618,
"label": "Prop 1"
},
{
"value": 2192,
"label": "Prop 3"
}
]
如果我对他的 defaultValue 进行硬编码,它可以工作,但不适用于来自变量的数据。
【问题讨论】:
-
你为什么使用
useEffect?你不能useState(props.location.user.properties)吗? -
我将状态初始化为空,如果定义了
props.location.user,则 useEffect 设置状态数据。否则,我重定向页面。
标签: reactjs react-select