在React中,选择表单的`onChange`事件显示了数组中的前一个对象。

huangapple go评论81阅读模式
英文:

onChange for select form in React showing previous object in array

问题

我正在使用React和Bootstrap创建一个简单的选择下拉表单。下拉菜单中的选项是从应用程序数据库中检索的“region”对象数组填充的。我的问题是,当我点击下拉菜单中的选项时,第一次点击会在控制台中记录来自API的404错误。第二次点击会记录我之前点击的第一个项目,第三次点击会显示我之前点击的第二个项目,依此类推,每次点击都会产生前一个项目的数据。

我正在使用的表单如下:

<Form>
    <select className="form-control" onChange={handleRegionChange}>
        <option>Select a Region</option>

        {regions.map((region) =>
        <option
            value={region.id}
            key={region.id}
        >
        {region.country}
        </option>
        )}
    </select>
</Form>

我使用的handleRegionChange函数如下。请注意,即使在第三行没有使用附加的retrieveRegion步骤来使用从表单传递的id获取区域,我仍然遇到相同的问题。控制台记录第一个项目点击的id为null,然后记录前一个项目的id,依此类推。

const handleRegionChange = (e) => {
    setRegionId(e.target.value);
    retrieveRegion(regionId);
    console.log(regionId);
}

以下是我的函数设置:

const [regions, setRegions] = useState([]);
const [currentRecipe, setCurrentRecipe] = useState(initialRecipeState);
const [regionId, setRegionId] = useState();
const [currentRegion, setCurrentRegion] = useState();
const [regionRecipe, setRegionRecipe] = useState(initialRegionRecipeState);

useEffect(() => {
    retrieveRegions();
    retrieveRecipe(id);
}, []);

以下是点击选择选项后显示数据的屏幕截图,以演示问题。首先,我点击墨西哥,它显示法国,然后我点击美国,它显示墨西哥。同样,当我尝试仅在选定的选项的值上记录id时,这个问题也会发生。

总结:
我尝试从对象数组创建下拉选择表单。我期望能够点击下拉表单中的一个选项,并获取与该项目关联的id的值。但实际上,我一直得到的是之前选定选项的id的值。

英文:

I'm creating a simple select dropdown form in React using Bootstrap. The options in the dropdown are populated from an array of "region" objects retrieved from the app's database. My problem is that when I click on an options from the dropdown, the first item click console logs a 404 error from the api. The second click console logs the first item I clicked on, the third click shows the second item I clicked on and so on, so that every click yields the data for the previous item clicked on.

The form I'm using:

&lt;Form&gt;
    &lt;select class=&quot;form-control&quot;  onChange={handleRegionChange} &gt;
        &lt;option&gt;Select a Region&lt;/option&gt;

        {regions.map((region) =&gt; 
        &lt;option
            value= {region.id}
            key={region.id}
        &gt;
        {region.country}
        &lt;/option&gt;
        )}
    &lt;/select&gt;
&lt;/Form&gt;

The handleRegionChange function I'm using looks like this. Note, that even without the additional retrieveRegion step on the third line to get the region using the id passed from the form, I still have the same issue. The console log shows null for the id of the first item clicked on, then the id for the previous item, etc.

 const handleRegionChange = (e) =&gt; {
    setRegionId(e.target.value);
    retrieveRegion(regionId)
    console.log(regionId)
  }

Here's the setup for my functions:

const [regions, setRegions] = useState([]);
const [currentRecipe, setCurrentRecipe] = useState(initialRecipeState);
const [regionId, setRegionId] = useState()
const [currentRegion, setCurrentRegion] = useState ()
const [regionRecipe, setRegionRecipe] = useState(initialRegionRecipeState);


useEffect(() =&gt; {
    retrieveRegions();
    retrieveRecipe(id);
  }, []);

Screenshots with data displayed after clicking on select option to demonstrate the problem. First I click on Mexico and it shows France, then I click on the US and it shows Mexico. Again, this problem also occurs when I simply try to console log the id from the value of the option selected. [在React中,选择表单的`onChange`事件显示了数组中的前一个对象。](https://i.stack.imgur.com/ke7st.png)

Summary:
I tried to create a dropdown select form from an array of objects. I expected to be able to click on one of the options in the dropdown form and get the value of the id associated with that item. Instead I keep getting the value of the id for the previously selected option.

答案1

得分: 1

React中的状态更新是异步的;当请求更新时,更新不会立即进行。
但是你可以在useEffect钩子中跟踪状态的变化。

const handleRegionChange = (e) => {
  setRegionId(e.target.value); // 这里regionId被正确设置
  retrieveRegion(regionId)
  console.log(regionId);   // 但是React不会立即更新状态,这将是之前的值。
}

// 如果你想在设置新状态后执行某些操作,可以使用useEffect来跟踪新状态。
useEffect(() => {
  console.log(regionId); // 更新后的regionId
}, [regionId]);

注意:修正了console.log(regionId). 中的错误,将.改为;

英文:

State updates in React are asynchronous; when an update is requested, updates will not be made immediately.
But you can track the state changes in the useEffect hook.

const handleRegionChange = (e) =&gt; {
  setRegionId(e.target.value); // Here the regionId was set correctly
  retrieveRegion(regionId)
  console.log(regionId).   // But React doesn&#39;t update the state immediately and this will be the previous value.
}

// If you want to do something after setting new state, you can use useEffect to track the new state.
useEffect(() =&gt; {
  console.log(regionId); // Updated regionId
}, [regionId];

答案2

得分: 1

**使用 event.target.value**

const [regionId, setRegionId] = useState()

const handleChange = async (event) => {
    setRegionId(event.target.value)
    console.log(regionId)
}
useEffect(() => {
    console.log(regionId)
}, [regionId];

**或者如果不使用 async/await可以这样使用**

const [regionId, setRegionId] = useState()

<select class="form-control"
    onChange={(e) => setRegionId(e.target.value)} 
    value={regionId}>
    <option>Select a Region</option>

    {regions.map((region) => 
        <option
            value= {region.id}
            key={region.id}
        >
        {region.country}
        </option>
    )}
</select>
英文:
   **use event. target.value**
  
  const [regionId, setRegionId] = useState()
  
  const handleChange = async (event) =&gt; {
      setRegionId(event.target.value)
      console.log(regionId)
  }
  useEffect(() =&gt; {
  console.log(regionId)
  }, [regionId];

   **or if you do not use async/await, use like this** 
  
  const [regionId, setRegionId] = useState()
  
  
   &lt;select class=&quot;form-control&quot; 
      onChange={(e) =&gt; setRegionId(e.target.value)} 

  
    value={regionId}&gt;
          &lt;option&gt;Select a Region&lt;/option&gt;
  
          {regions.map((region) =&gt; 
          &lt;option
              value= {region.id}
              key={region.id}
          &gt;
          {region.country}
          &lt;/option&gt;
          )}
      &lt;/select&gt;

huangapple
  • 本文由 发表于 2023年7月11日 10:01:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76658300.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定