我正在尝试设置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进行硬编码,它可以工作,但不能使用来自变量的数据。
尝试这个例子,您可以在声明代码沙盒时分配初始状态