【问题标题】:react-select defaultValue not loading from Statereact-select defaultValue 未从状态加载
【发布时间】: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 没有显示任何内容。

日志,起初propertiesselectedProps 都是空的。然后,它具有值的第二个日志: 属性:

[
   (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


【解决方案1】:

试试这个例子,你可以在声明时分配初始状态Code Sandbox

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 2020-08-24
    • 2015-07-20
    • 2019-08-21
    • 1970-01-01
    • 2020-08-24
    相关资源
    最近更新 更多