【问题标题】:Why initial value of dropdown not set in react?为什么没有在反应中设置下拉菜单的初始值?
【发布时间】:2020-01-27 05:02:30
【问题描述】:

你能告诉我为什么我的初始值没有在反应中设置吗?我正在使用react-final-form

这是我的代码

https://codesandbox.io/s/frosty-star-1qcw3

我的初始值打印在控制台中,但没有设置在下拉菜单中

react final 形式的API链接

https://final-form.org/docs/react-final-form/examples

const [options, setOptions] = useState([]);
  useEffect(() => {
    console.log("urllll");

    // (async () => {
    //   setOptions(await getDropDowOptions(dataKey));
    // })();
    console.log(options);
    console.log(value);
    (() => {
      setOptions(getDropDowOptions(dataKey));
    })();
  }, []);





const getDropDowOptions = dataKey => {
  console.log(dataKey);
  switch (dataKey) {
    case "abc":
      console.log("========");
      const slots = [
        {
          key: "9-13",
          label: "09:00-13:00",
          value: "09:00-13:00"
        },
        {
          key: "13:00-16:00",
          label: "13:00-16:00",
          value: "13:00-16:00"
        },
        {
          key: "16:00-19:00",
          label: "16:00-19:00",
          value: "5000"
        }
      ];
      return slots;
  }
};

【问题讨论】:

    标签: javascript reactjs react-final-form final-form


    【解决方案1】:

    您似乎正在将您的状态初始化为一个空数组,这会在设置AutoComplete 中的defaultValue 时产生一个要过滤/查找的空数组。将选项直接填充到 state 的初始值中对我来说在你的沙箱中是有用的。

    const [options, setOptions] = useState(getDropDowOptions(dataKey));
    

    我的猜测是效果会在第一次渲染时触发并设置一些状态,但该状态在下一个渲染周期(即第二次渲染)之前不可用。到那时,选择已经设置了它的默认值(从第一次渲染时开始)。

    【讨论】:

    • async 请求呢
    • options.find is not a function
    • async 请求呢?您是在询问在装载和获取一些数据后设置一些“初始”状态吗?
    • 查看我的代码沙箱..举个例子,我正在从服务器获取数据..但我知道我的初始值是什么
    • 5 秒后我从服务器获取数据。不是我想设置我的价值吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 2021-12-03
    相关资源
    最近更新 更多