react-select defaultValue 未从 State 加载
react-select defaultValue not loading from State
我正在尝试为我的 react-select
设置默认值,但它无法正常工作。
import Select from 'react-select';
我有 selected 属性的状态
const [ selectedProps, setSelectedProps ] = useState([]);
在我的 useEffect 中,我设置了来自道具的值
setSelectedProps(props.location.user.properties);
就在渲染组件之前,我记录了数据以确保它是正确的
console.log(properties);
console.log(selectedProps);
这是我的 select
<Select
defaultValue={selectedProps}
isMulti
name="properties"
options={properties}
className="basic-multi-select"
classNamePrefix="select"
onChange={handleChangeProperties}
/>
默认值没有显示任何内容。
日志,一开始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 进行硬编码,它会起作用,但不适用于来自变量的数据。
试试这个例子,你可以在声明它时分配初始状态Code Sandbox
我正在尝试为我的 react-select
设置默认值,但它无法正常工作。
import Select from 'react-select';
我有 selected 属性的状态
const [ selectedProps, setSelectedProps ] = useState([]);
在我的 useEffect 中,我设置了来自道具的值
setSelectedProps(props.location.user.properties);
就在渲染组件之前,我记录了数据以确保它是正确的
console.log(properties);
console.log(selectedProps);
这是我的 select
<Select
defaultValue={selectedProps}
isMulti
name="properties"
options={properties}
className="basic-multi-select"
classNamePrefix="select"
onChange={handleChangeProperties}
/>
默认值没有显示任何内容。
日志,一开始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 进行硬编码,它会起作用,但不适用于来自变量的数据。
试试这个例子,你可以在声明它时分配初始状态Code Sandbox