【问题标题】:Select in ReactJS is picking up previous value after API call at onChange function?在 onChange 函数调用 API 后,ReactJS 中的 Select 会获取先前的值吗?
【发布时间】:2021-02-23 15:42:53
【问题描述】:

嗨, 我的要求是,当用户选择一个选项时,例如:回形针,onChange 函数调用另一个名为 getItem() 的函数,该函数调用 API 并从数据库中获取当前项目详细信息并将其存储在 currentItem 变量中。现在我想在用户选择一个选项后立即用 currentItem.unitPrice 更新单价输入框。 目前,单价正在使用先前选择的值而不是当前选择的值进行更新。所以,如果我选择回形针,什么都不会发生(null),但是当我选择第二个选项(打印机安装)时,它会用上一个值(回形针的单价)更新 不知道怎么回事,求大神帮忙。

 {inputList.map((x, i) => (
            <div className='form-group row'>
              <div className='input-group col-sm-2'>
<select
  className='form-control '
  name='item'
  value={x.item}
  onChange={(e) => handleInputChange(e, i)}
  required
>
  <option value='' disabled selected hidden>
    Item
  </option>
  {items.map((item) => (
    <option key={item._id} value={item._id}>
      {item.name}
    </option>
  ))}
</select>
const handleInputChange = (e, index) => {
  e.preventDefault();
  const { name, value } = e.target;
  const list = [...inputList];

  if (name === "item") {
    getItem(value);
    list[index]["unitPrice"] = currentItem && currentItem.unitPrice;
    setInputList(list);
  }

  list[index][name] = value;
  setInputList(list);
};


export const getItem = id => async dispatch => {
  try {
    const res = await axios.get(`/api/item/${id}`);

    dispatch({
      type: types.GET_ITEM,
      payload: res.data.data
    });
  } catch (err) {
    dispatch({
      type: types.ITEM_ERROR,
      payload: { msg: err.response.statusText, status: err.response.status }
    });
  }
};

【问题讨论】:

  • 我已经更新了帖子,请看一下,它实际上是我正在循环的字段数组,以便用户可以添加/删除输入行
  • @HenryLe 它是存储 getItem() 的结果的地方 getItem 基本上是一个获取当前项目数据的 API 调用,所以它已经获得了当前项目的所有详细信息,从那里我需要 currentItem.unitPrice
  • 我认为问题出在函数handleInputChange中的getItem(value)。你能显示你的函数 getItem
  • @HenryLe 我已经更新了帖子,请看一下

标签: reactjs react-redux react-hooks


【解决方案1】:
if (name === "item") {
    getItem(value);
    list[index]["unitPrice"] = currentItem && currentItem.unitPrice;
    setInputList(list);
  }

因为选择on Chage时,值currentItem为null(获取API不输入)。在第二个onChange中,currentItem之前已经加载成功,所以会在currentItem之前取回数据

const [selected, setSelected] = useState(-1);
const handleInputChange = (e, index) => {
  e.preventDefault();
  const { name, value } = e.target;
  let list = [...inputList];

  if (name === "item") {
    getItem(value);
  }
  setSelected(index)
  list[index][name] = value;
  setInputList(list);
};
useEffect(() => {
   if(currentItem._id){
      let list = [...inputList];
      list[selected]["unitPrice"] = currentItem.unitPrice;
      setInputList(list);
   }
}, [currentItem._id])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-26
    • 2019-06-01
    • 2019-09-30
    • 1970-01-01
    • 2021-10-18
    • 2023-02-04
    • 1970-01-01
    • 2018-06-20
    相关资源
    最近更新 更多